1

I use the jQuery Validate plugin to validate a form, and I want a value to be either below 26 or above 30. How can I do this?

I tried:

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

but then it just takes the last range, so if the value is below 40, it throws an error even if it's below 26 too.

Any suggestions?

Helge
  • 823
  • 5
  • 13
  • 28

1 Answers1

4

There doesn't appear to be a way to do this using the plug-in itself, but several people have suggested using a regular expression to validate ranges.

This resource demonstrates how to add a regex method to the validator:

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

I also took this a step further and wrote a plug-in to handle multiple ranges:

 $(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>
Community
  • 1
  • 1
jamesmortensen
  • 33,636
  • 11
  • 99
  • 120