views:

274

answers:

2

Hello, I have a problem with jQuery Validator. I want to use "required" property on a text input. It doesn't work when input has set value attribute by HTML code (tested on Firefox (3.5), and on IE 8 - on IE it works a bit better).

Story: 1. Page loads; 2. value is cleared; 3. focus is changed. 4. Nothing happens but the error message should be displayed; 5. getting back to the field and typing some characters. 6. changing focus; 7. getting back to the field; 8. clearing the field. 9. Error is displayed even before leaving the field.

The HTML code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <script src="Web/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="Web/Scripts/jquery.validate.js" type="text/javascript"></script>    
</head>
<body>
    <form id="form1">
        <input type="text" id="name1" name="name1" value="test" /><br />
        <input type="text" />
    </form>

    <script type="text/javascript">
        $(document).ready(function() {
            var validator = $("form").validate({

                rules: {
                    name1: {
                        required: true,
                        minlength: 2
                    }
                },
                messages: {
                     name1: "bad name"
                },
            });
        });
    </script>
</body>
</html>
A: 

Hi,

you forgot to say which validation the message was for: try this:

 messages: { 
             name1:
                   {
                      required : "This is a required field",
                     minlength: "Please enter 2 chars or more"
                   }
            }

Michel

Michel
It's not necessary. If you provide only one message it used always. Even so, it's not the case, because in "step 9" the validations starts to work correctly.
hmm, didn't read the question good enough.
Michel
A: 

You can override the onfocusout handler to make this work like you want (more eager):

$(function() {
    var validator = $("form").validate({
        rules: { name1: { required: true, minlength: 2 } },
        messages: { name1: "bad name" },
        onfocusout: function(element) { $(element).valid(); }
    });
});

You can see the old broken demo (like your question) here and the updated one with onfocusout that works here.

Nick Craver