6

I would like to add a custom rule to jQuery validate, and while I have checked the docs I have not been able to find out how to do this.

I want to loop over a set of hidden form fields. If the fields value is "X", then I would like to append an error class to a field.

So essentially this, but added as a rule to jQuery validate.

$(".myHiddenField").each( function() {
   if($(this).val() == "x") {
    $(this).closest(".foo").appendClass("error");
   }
});
2
  • you want loop this input, you should $(".myHiddenField input").each( function() {}) Commented Jul 10, 2013 at 2:44
  • Areschen, I am not asking how to select the element - rather how to implement this within the jQuery validate fw. Commented Jul 10, 2013 at 2:46

3 Answers 3

12

You may use addMethod()

$.validator.addMethod('yourRuleName', function (value, element, param) {
    //Your Validation Here

    return isValid; // return bool here if valid or not.
}, 'Your error message!');


$('#myform').validate({
    rules: {
        field1: {
            yourRuleName: true
        }
    }
});
Sign up to request clarification or add additional context in comments.

6 Comments

Let me give this a try. Thanks!
English please..You should not use your local language so your comment may help other people too.. =)
Ayon sa translate.google:What's that? yourRuleName whatever name? or dun depend on class, attribute or id?
Ohh.. Yup, it is the name of your validation rule, you may use any name you want.
I am still not following. In your example, how is it applying the error class to the closest field?
|
1

If you want to show some custom error messages without adding an actual rule then you can use the showErrors() method, but if you are working on a hidden field it may not work

var validator = $( "<form-selector>" ).validate();

var errors = {};
$(".myHiddenField").each( function() {
    var $this = $(this);
    if($this.val() == "x") {
        errors[$this.attr('name')] = 'Some error message';
    }
});

validator.showErrors(errors);

Comments

0
$.validator.addMethod("NOTx", function(element,value) {
    return  value != "x";
}, 'warning word"!');

1 Comment

It's very bad to show how to create some customization but not to show how to use it. The answer from Nikko Reyes is way better than yours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.