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");
}
});
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");
}
});
Share
Improve this question
asked Jul 10, 2013 at 2:36
Jason WellsJason Wells
8896 gold badges16 silver badges33 bronze badges
2
- you want loop this input, you should $(".myHiddenField input").each( function() {}) – momo 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. – Jason Wells Commented Jul 10, 2013 at 2:46
3 Answers
Reset to default 12You 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
}
}
});
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);
$.validator.addMethod("NOTx", function(element,value) {
return value != "x";
}, 'warning word"!');