0

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

在上面的示例中,如果当前选定元素的值 == 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 / 验证

$('#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')
        }
    }
});
4

1 回答 1

0
add 
  submitHandler: function(form) {

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

你也可以set value="0" to ""像@arun 说的那样

演示

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

于 2013-10-18T13:15:08.260 回答