OrangeTux
OrangeTux

Reputation: 11471

jQueries validation plugin shows always on input

I'm stuck with jQueries validation plugin

My input give me always an error. Code can you find here: http://jsfiddle.net/OrangeTux/6zUMd/1/

I want to create some custom rules, like postalcode, phonenumber and some other specific numbers. Therefore, I create a new method for the regular expression rule. This rule works correctly.

$.validator.addMethod("regexp", function(value, element, param) {
     return this.optional(element) || !param.test(value);
});

After that I create a new method:

jQuery.validator.addMethod('postalCode', function(value, element) {});

Then I use create a new class and add the rules

//add validation rules for each custom method
jQuery.validator.addClassRules({
   postalCode: {
      'postalCode' : true,

       //regexp: /[^[0-9]{10}$]/, //<---- This regex doesn't work
       //email: true              // <----- This rule doens't work either
   }
})

How can I solve this?

Upvotes: 1

Views: 699

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

You've got a few things a bit backwards. First of all, the regex rule is not quite right. You want to return true from the method when the rule passes, so you should return:

return this.optional(element) || param.test(value);

Beyond that though, the preferred way for adding a custom rule like this is to use addMethod, and then addClassRules to add a class rule that includes that method:

jQuery.validator.addMethod("postalCode", function (value, element, params) {
    return this.optional(element) || /^[0-9]{10}$/.test(value);
}, "Please enter a valid Postal Code");

//add validation rules for each custom method
jQuery.validator.addClassRules({
    postalCode: {
        postalCode: true
   }
});

$("#form").validate({
    debug: true,

    //set place were error is shown
    errorPlacement: function(error, element) {
        error.appendTo(element.parent("td").next("td"));
    },
});

Example: http://jsfiddle.net/LCA9C/

Upvotes: 1

Related Questions