jquery验证在页面上不起作用

时间:2015-01-19 14:14:23

标签: jquery jquery-validate

我已经在我的HTML页面上找到了此表单

<div class="box fl-panel" id="wrap">
    <form id="sign_in" name="sign_in" class="fm-v" action="" method="post" onsubmit="Javascript:void(0)">
        <table border="0" cellpadding="0" cellspacing="0" width="100%">
        <tbody>
            <tr>
                <td class="form_head" colspan="2">Sign In</td>
            </tr>
            <tr>
                <td class="form_username">
                    <label for="user_name" class="fl-label">Email:</label>
                </td>
                <td class="form_username_input">
                    <input id="user_name" name="Email" class="required" tabindex="1" accesskey="u" size="25" autocomplete="false" type="text">
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td class="form_submit">
                    <input name="lt" value="*" type="hidden">
                    <input id="submit_sign_in" class="btn-submit" name="submit" accesskey="l" value="Send" tabindex="4" type="submit">
                </td>
           </tr>
        </tbody>
        </table>
    </form>
</div>

body代码的页面上,我设置了script个代码。

<script type="text/javascript" src="login/jquery.js"></script>
<script type="text/javascript" src="login/jquery-ui.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>        
<script type="text/javascript">
$(function(){
    $("#sign_in").validate({
            rules: {
                user_name: "required"
            },
            messages: {
                user_name: "Wrong email"
            },
            submitHandler: function(form) {
                form.submit();
            }
    });
});
</script>

使用jquery validation插件。 但是,当我点击按钮Send时 - 什么也没发生。 浏览器控制台中也没有。 怎么了?

1 个答案:

答案 0 :(得分:0)

jQuery Validate插件的.validate()方法使用name属性,而不是id

rules: {
    user_name: "required"  // <- "user_name" must be the NAME attribute
},
messages: {
    user_name: "Wrong email"  // <- "user_name" must be the NAME attribute
},

class="required"中您不需要input,因为您已在required方法中声明了.validate()规则。

<强> HTML

<input id="user_name" name="user_name" tabindex="1" accesskey="u" size="25" autocomplete="false" type="text">

此外,您的submitHandler是多余的......

submitHandler: function(form) {
    form.submit();
}

这已经是默认行为,因此没有理由指定它。换句话说,您可以完全删除submitHandler

name属性更改为user_name后,这将是正常工作的代码......

$(function(){
    $("#sign_in").validate({
        rules: {
            user_name: "required"
        },
        messages: {
            user_name: "Wrong email"
        }
    });
});   

工作演示:http://jsfiddle.net/vupdnd34/