vaibhav
vaibhav

Reputation: 351

Regex is not displaying correct error message

I am trying to use the validation for the field rate_model.I have used Jquery validate for this. rate_model should accept two types of format

1. Number,number (if user enters only two number)
2. Number,number;number,number (if user enters more than two number it should be separated by ; (semicolon) )

These are my validation scenarios.

$(document).ready(function(){    
$.validator.addMethod("regex_rate",function(value, element, regexp) {          
        return this.optional(element) || regexp.test(value);  });
$("#frm_add_country").validate({
        rules: {
        rate_model: {
            required: true,
            regex_rate:/^([0-9],[0-9])|([0-9],[0-9];)$/
        }
    },
    messages: {
        rate_model: {
            required: "Please enter description",            
            regex_rate: "please enter (number,number) or (number,number);(number,number) ",            
        },        
    },
    submitHandler: function (form) {
        console.log("true");
    }
});
});

This is my jquery validation

<form id="frm_add_country" name="frm_add_country" method="post">
<input type="text" id="rate_model" name="rate_model" class="form-control" >
</form>

this is my form filed

/^([0-9],[0-9])|([0-9],[0-9];)$/ 

this regular expression is not working for my expected scenarios

Upvotes: 0

Views: 42

Answers (2)

Toto
Toto

Reputation: 91385

This regex does the job

/^\d+,\d+(?:;\d+,\d+)*$/

Explanation:

/           : regex delimiter
  ^         : begining of string
    \d+     : 1 or more digits
    ,       : a comma
    \d+     : 1 or more digits
    (?:     : start non capture group
      ;     : a semicolumn
      \d+   : 1 or more digits
      ,     : a comma
      \d+   : 1 or more digits
    )*      : end group, 0 or more times
  $         : end of string
/           : regex delimiter

Upvotes: 2

laughing buddha
laughing buddha

Reputation: 361

@toto is correct.
just one correction, if there are still more number like - 15,16;17,18;19,20 so on
we need to append * as well at the end. So it will be

/^\d+,\d+(?:;\d+,\d+)*?$/

Explanation:

/           : regex delimiter  
  ^         : beginning of string  
    \d+     : 1 or more digits  
    ,       : a comma  
    \d+     : 1 or more digits  
    (?:     : start non capture group  
      ;     : a semicolon     
      \d+   : 1 or more digits  
      ,     : a comma
      \d+   : 1 or more digits  
     )*     : end group, one or more repetition  
    ?       : optional  
  $         : end of string  
/           : regex delimiter  

Upvotes: 1

Related Questions