jquery - 在 jquery 验证器中添加自定义方法

标签 jquery validation

我正在学习jquery验证器插件。我创建了自定义验证器方法并将其应用于名字输入。但它不起作用,并且添加其他验证后也无法正常工作。我只是想知道我做错了什么。

Fiddle

$.validator.setDefaults({
    submitHandler: function(){
    alert("form submited")
}
})  


$('#theform').validate({
    rules:{
    fname:{
    required:true,
    name:true
    },
    lname:"required",
    username:{
    required:true,
    minlength:2
    }           
},
messages:{
    fname:"first name is required",
    lname:"last name is required",
    username:{
    required:"this field is required",
    minlength:"atleast two charactor is required"
    }

    }


})

jQuery.validator.addMethod("name", function(a, b) {
    return a.indexOf('john')!=-1;
    }, "Please enter name john");

最佳答案

http://jsfiddle.net/44funjz2/5/

HTML

<form id="theform">

...
        <label>name</label>
        <input type="namevalidation" id="fname" name="fname" required />
...

</form>

JQ

//to add validator method for name
//1. change input type e.g. "namevalidation"
//2. in addMethod for name take mentioned value: "namevalidation"
//3. addMethod methods must go before attaching validate plugin
$.validator.addMethod("namevalidation", function (a, b) {
    return a.indexOf('john') != -1;

}, "Please enter name john");


$('#theform').validate({
    //pay attention to the creation of rules and use {} for each rule
    rules: {
        fname: {
            required: true,
        },
        lname: {
            required: true,
        },
        username: {
            required: true,
            minlength: 2

        }
    },
    //use {} for each message
    messages: {
        fname: {
            required: "first name is required"
        },
        lname: {
            required: "last name is required"
        },
        username: {
            required: "this field is required",
            minlength: "atleast two charactor is required"
        }

    }

});

关于jquery - 在 jquery 验证器中添加自定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27191468/

相关文章:

javascript - 语法错误: Unexpected end of input (jQuery)

sql - 基于 FK 关系的约束表

ruby-on-rails - 在 Rails 3.2 + SimpleForm 中显示带有嵌套表单错误的字段

xcode - 始终将 “Network connection was lost”作为验证问题

jQuery cookie 过期值

javascript - Highstock dateTimeLabelFormats 不起作用

php - 哪个验证规则用于 Laravel 4 的 float ?

html - 选择必需的验证在表单中不起作用

javascript - 图像和段落交错的问题

javascript - Chrome 的窗口调整大小事件问题