jQuery Validate not triggering

爱⌒轻易说出口 提交于 2019-12-20 07:04:25

问题


I have the following html and js, but it is not triggering the jquery.validate validation on text input field blur or form submit. If I add "required" attribute directly to the text input field, the default error message kicks in instead. Can anyone please help me figure out why the below does not work?

<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.validate.min.js"></script>
<script type="text/javascript" src="jquery.validate.unobtrusive.min.js"></script>

</head>
<body>
    <form id="test" action="test.html" method="post">
        <input type="text" name="txtName" />    
        <input type="submit" name="btnSubmit" />
    </form>
</body>
</html>
<script type="text/javascript">
    $(document).ready(function(){
        ValidateForm();

    });

    function ValidateForm(){
        $.validator.unobtrusive.parse($("form"));

        $('#test').validate({
            rules: {
                "txtName": "required"
            },
            messages: {
                "txtName": "this name is required for sure!"
            },
            errorPlacement: function (error, element) {
                $(element).parent().append(error);
            },
            onfocusout: function (element) { this.element(element); }
        });
    }
</script>

回答1:


<script type="text/javascript" src="jquery.validate.unobtrusive.min.js"></script>

Why are you including the unobtrusive plugin?

You cannot simultaneously use the unobstrusive plugin while calling the .validate() method yourself.

Why?

Because the unobtrusive plugin automatically constructs and calls the .validate() method based on the HTML attributes.

Since the plugin only uses the first call to .validate() to initialize validation, it automatically ignores all subsequent calls. So your call to .validate() is totally ignored.

If i add "required" directly to the text input field, the default error message kicks in instead.

Because of the unobtrusive plugin, your call to .validate() is totally ignored by jQuery Validate. That is why it only works when you put the required attribute within your input element.

Completely remove the unobtrusive plugin and it works fine:

http://jsfiddle.net/ocx864nu/



来源:https://stackoverflow.com/questions/30608345/jquery-validate-not-triggering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!