jQuery Validation plugin with a custom attribute [closed]

不羁的心 提交于 2019-12-17 16:31:34

问题


I want to use the jQuery Validation plugin with this HTML:

<input data-validators="required" name="X2aasNr" type="text" value="Nedas" class="cleared" id="">

As you can see, I use a custom attribute named data-validators. How can I use the jQuery Validation plugin for this case?


回答1:


Quote OP:

<input data-validators="required" ...

"As you can see, I use a custom attribute named data-validators. How can I use the jQuery Validation plugin for this case?"

You can't. The plugin was not written to recognize that attribute.

See: http://jsfiddle.net/y5xUF/

However, you can define validation rules as per the following methods:


1) Declared within .validate()

$(document).ready(function() {

    $('#myform').validate({
        rules: {
            fieldName: {
                required: true
            }
        }
    });

});

http://jsfiddle.net/uTt2X/2/

NOTE: If your field name contains special characters such as brackets or dots, you must enclose the name in quotes...

$(document).ready(function() {

    $('#myform').validate({
        rules: {
            "field.Name[234]": {
                required: true
            }
        }
    });

});

2) Declared by class:

<input name="fieldName" class="required" />

http://jsfiddle.net/uTt2X/1/


3) Declared by HTML5 validation attributes:

<input name="fieldName" required="required" />

http://jsfiddle.net/uTt2X/


4) Declared using the .rules() method:

$('input[name="fieldName"]').rules('add', {
    required: true
});

http://jsfiddle.net/uTt2X/3/


5) By assigning one or more rules to your own class using the .addClassRules() method:

$.validator.addClassRules("myClass", {
    required: true 
});

Then apply to your HTML:

<input name="fieldName" class="myClass" />

http://jsfiddle.net/uTt2X/4/




来源:https://stackoverflow.com/questions/17789372/jquery-validation-plugin-with-a-custom-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!