Question

There is an text field id_number and for the data to be entered in this field should satisfy the following conditions

  1. The first 2 letters must be "MU" or "mu"

  2. No spaces or special character will be allowed

If the value in id_number doesn't match the 2 above condition then "Please enter valid ID e.g, MUXYZ001" will be displayed.

For this I have written a short custom validation rule:

{literal}
jQuery.validator.addMethod("checkId", function(value, element) {
var id_val = $("#id_number").val();
var string1=id_val.substr(0,2);
var badchars = /[<>$@&+()[\]{},` ]/;

if ( (string1=='mu') && (!(badchars.test(id_val)))){ 
               return false;
          }else{
              return true;
          }
}, "Please enter valid ID e.g, MUXYZ001");{/literal}

and the custom rule :

rules: {
         id_number: {checkId: true}
       }   

but it's not working ..

Someone kindly fix it for me.

Was it helpful?

Solution

UPDATED

Use regex instead, see this sample snippet to get the idea:

{literal}
jQuery.validator.addMethod("checkId", function(value, element) {
var id_val = $("#id_number").val(); 
       var reg= new RegExp("^mu\\d{2}\\D+$","i"); 
       if (reg.test(id_val)){ 
                   return true;
       }else{
           return false;
       }
}, "Please enter valid ID e.g, MUXYZ001");{/literal}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top