jQuery validate plugin:多个范围内的值

时间:2011-01-09 06:27:17

标签: jquery error-handling validation

我使用jQuery Validate插件来验证表单,我想要一个低于26或高于30的值。我该怎么做?

我试过了:

forum_id: { required: true, range: [0,26], range:[40,100] }

但是它只取最后一个范围,所以如果该值低于40,即使它也低于26也会引发错误。

有什么建议吗?

1 个答案:

答案 0 :(得分:4)

似乎没有办法使用插件本身,但有几个人建议使用正则表达式来验证范围。

此资源演示了如何将正则表达式方法添加到验证器:

jQuery validate: How to add a rule for regular expression validation?

我还更进一步,编写了一个插件来处理多个范围:

 $(document).ready(function() {

 $.validator.addMethod(
    "ranges",
     function(value, element, ranges) {
        var noUpperBound = false;
        var valid = false;
        for(var i=0; i<ranges.length; i++) {
            if(ranges[i].length == 1) { 
                noUpperBound = true;
            }
            if(value >= ranges[i][0] && (value <= ranges[i][1] || noUpperBound)) {
                valid = true;
                break;
            }            
        }

        return this.optional(element) || valid;
    },
    "Please check your input."
 );


 $("#myform").validate({
     submitHandler: function(form) {
        if(form && form.submit) form.submit();
     } 
 });

 // range must be between 0 to 25 OR greater than 30
   // represented as an array of size-2 arrays.
 $("#age").rules('add', { ranges: [ [0,25], [31] ] });


 <form id="myform" action="#">
    <span>age</span><input type="text" id="age" name="age" />
    <input type="submit" name="submit" value="submit" />
 </form>