Jquery验证插件,选择值验证

时间:2013-10-18 13:07:10

标签: jquery jquery-validate

我在提交前使用jquery验证来验证我的表单,如何在提交之前验证选择框值?

在上面的示例中,如果当前所选元素的值为== 0,则我希望验证失败。

HTML

<form action="/foo" id="register_form" method="post">
  <select id="city_select" name="city_id">
    <option value="0">Select City</option>
    <option value="4">New York</option>
    <option value="24">Chicago</option>
    <option value="25">Washington</option>
   </select>

    <input class="" id="username" name="username" type="text" /><br/>
    <input class="" id="email" name="email" placeholder="Email" type="text" /><br/>
    <input class="" id="password1" name="password1" type="password" />
    <input class="" id="password2" name="password2" type="password" /><br/>

    <input type="checkbox" value="1" name="terms_of_use" id="terms_of_use">
</form>

Jquery / Validate

$('#register_form').validate({
    onfocusout: function (element, event) {

},
    rules : {
        username: {
            required: true
        },
        email: {
            required: true,
            email: true
        },
        terms_of_use: {
            required: true
        },
        password1: {
            required: true,
                            rangelength: [5, 50]
        },
        password2: {
            required: true,
            equalTo: '#password1'
        }
    },
    messages: {
        username: {
            required: I18n.t('validation.register.username')
        },
        city_id: {
            required: I18n.t('validation.register.city')
        },
        email: {
            required: I18n.t('validation.register.email'),
            email: I18n.t('validation.register.email_f')
        },
        terms_of_use: {
            required: I18n.t('validation.register.tos')
        },
        password1: {
            required: I18n.t('validation.register.password1'),
            rangelength: I18n.t('validation.register.password_l')
        },
        password2: {
            required: I18n.t('validation.register.password2'),
            equalTo: I18n.t('validation.register.password_match')
        }
    }
});

1 个答案:

答案 0 :(得分:0)

add 
  submitHandler: function(form) {

if($("#city_select")!==0) 
 {$(form).submit();
}else{
alert("select value");
}  
}

你也可以{@ 1}} @arun说

参见 demo

参考http://jqueryvalidation.org/documentation/