Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validator's "required" not working when value is set at statup

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">
<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>
like image 621
andrew.fox Avatar asked Jan 23 '10 17:01

andrew.fox


1 Answers

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.

like image 65
Nick Craver Avatar answered Oct 09 '22 09:10

Nick Craver