3

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
  • 1
    Since this has been marked off-topic for some reason I'll give a summary - create a global rule with addMethod. Then add it as a class to the input. If you need to specify data for the validation you can read custom data-attributes in the addMethod callback (it passes value, element) Commented Feb 16, 2015 at 15:19

1 Answer 1

15

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/


6) Declared by field type:

<input name="fieldName" type="email" />

http://jsfiddle.net/gv0o6syt/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.