最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Creating a custom rule in jQuery Validate - Stack Overflow

programmeradmin3浏览0评论

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
Add a comment  | 

3 Answers 3

Reset to default 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
        }
    }
});

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"!');
发布评论

评论列表(0)

  1. 暂无评论