Search code examples
jqueryregexjquery-validation-engine

custom validation rule for integer range in jquery validation engine


I am using JQuery Validation Engine library. I am trying to create a custom validation either through Regex or custom method to validate the field input.

I would suggest this validation name as custom integer validation containing integer range or some integers separated by comma(s) or combination of both.

Here is the criteria:

  1. can enter any integer. For e.g. 89
  2. can enter any integer range. For e.g. 12-18 or 15-18 but not 19-3 (range should between min to max)
  3. can enter any combination of above two inputs separated by comma(,) only with or without spaces between comma. For e.g. 1-6, 5, 8-13, 7. But not -3-5 (not -3) or 3-7-, 10 (not 7-)

I tried this custom rule:

"integerRangeComma": {                    
             "regex": /^(([0-9]+)([\,]([0-9]+))?|([\,]([0-9]+))?)$/,
             "alertText": "* Invalid floating decimal number"
          },

My intended purpose to do the above validation is:

I have a list of total documents lets suppose 12. I created a text-box in the form to accept what document no, he likes to add in his profile. And the above criteria should be applied on that.

My next question would be, I also must validate that numbers entered by user do not greater than 12 (my presumption).

How can I achieve this either through creating my own custom rule or something else.

Thanks in Advance.


Solution

  • Doing maths with regex is always a pain, you should parse it and check the not greater than 12 condition with code. However, it is possible for this simple example by using

    [0-9]|1[12]
    

    Your combination for an input of a single integer or a range will then be

    number(-number)?
    

    and for one input, or two commaseparated ones is

    input(\s*,\s*input)?
    

    If you want more than two, use * for unlimited or {0,n} for limited repetion instead of the ?.

    So together, you get

    var integerRangeComma = {                    
         "regex": /^([0-9]|1[12])(-[0-9]|-1[12])?(\s*,\s*([0-9]|1[12])(-[0-9]|-1[12])?)?$/,
         "alertText": "a single page number until 12 or an interval in them, or two of those separated by a comma"
    };