jquery表单验证插件:字段1不等于字段2

时间:2011-10-26 15:55:48

标签: jquery jquery-plugins

heyho,

我遇到了以下问题:我试图阻止用户可以选择字段“username”和“email”相同的值。我正在使用jquery表单验证插件(http://bassistance.de/jquery-plugins/jquery-plugin-validation/)

如果有人能给我指路的话,那会很棒,请在这里查看我的代码:

// validate form    
$("#signupform").validate({

    rules: {
        username: {
            required: true,
            minlength: 2,
            remote: "/_misc/formcheck/username.cfm"
        },
        password1: {
            required: true,
            minlength: 5
        },
        password2: {
            required: true,
            minlength: 5,
            equalTo: "#password1"
        },
        email: {
            required: true,
            email: true,
            remote: "/_misc/formcheck/email.cfm"
        },
        email2: {
            required: true,
            email: true,
            equalTo: "#email"
        },
        usage: "required"                       
    },
    messages: {
        username: {
            required: "please username!!",
            minlength: "username at least 2 chars"
        },
        password1: {
            required: "please password!",
            minlength: "password at least 5 chars"
        },
        password2: {
            required: "please password",
            minlength: "password at least 5 chars",
            equalTo: "password fields have to match"
        },
        email: "validate email please!",            
        email2: {
            required: "please provide correct email address!",              
            equalTo: "email fields must match!"
        },
        usage: "please check my terms!" 
    }, 

提前感谢,michbeck

2 个答案:

答案 0 :(得分:21)

您可以添加自定义方法,检查用户名和电子邮件值,并为该字段添加验证。

演示 - http://jsfiddle.net/2hA8M/8/

示例 -

方法 -

$.validator.addMethod("user_email_not_same", function(value, element) {
   return $('#name').val() != $('#email').val()
}, "* User and Email should not match");

验证 -

rules : {
     username : {
         user_email_not_same: true
     }
 },

答案 1 :(得分:8)

这可能更灵活:

$.validator.addMethod("notEqualTo", function (value, element, param)
{
    var target = $(param);
    if (value) return value != target.val();
    else return this.optional(element);
}, "Does not match");

电话:

rules: {
    username: {
        required: true,
        minlength: 2,
        remote: "/_misc/formcheck/username.cfm",
        notEqualTo: "#emailId-or-anyValidJquerySelector"
    }
}

示例:http://jsfiddle.net/4AdWR/1/

或直接在Html:

<input type="text" name="username" notEqualTo="#emailId-or-anyValidJquerySelector" minlength="2" class="required" />

示例:http://jsfiddle.net/B2hWn/1/

这也尊重您所需的/可选的先前验证;)