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?

Sparky
  • 98,165
  • 25
  • 199
  • 285
user2580228
  • 49
  • 1
  • 4
  • 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`) – Dominic Feb 16 '15 at 15:19

1 Answers1

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/

Sparky
  • 98,165
  • 25
  • 199
  • 285