Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable to regular expression pattern string in jquery

Tags:

jquery

regex

Is that possible to pass variable into regular expression pattern string in jquery ( or javascript)? For example, I want to validate a zip code input field every time while user type in a character by passing variable i to the regular expression pattern. How to do it right?

 $('#zip').keyup( function(){ 
 var  i=$('#zip').val().length
 for ( i; i<=5; i++){   
            var pattern=/^[0-9]{i}$/;  
     if ( !pattern.test(   $('#zip').val()   )    )
                {$('#zip_error').css('display','inline');}   
     else
         {$('#zip_error').css('display','none');}
   }
 })
like image 951
Philip007 Avatar asked Jun 12 '10 07:06

Philip007


1 Answers

Yes, you can, using the RegExp constructor:

var pattern = new RegExp("^[0-9]{"+i+"}$");

But... looking at your code seems that you want to ensure that the textbox contains only numbers, for that you can use a simple regex like this:

var pattern = /^[0-9]+$/;

The above pattern will only match a string composed by numbers, it will look for:

  • Beginning of a line ^
  • Match a single digit character [0-9]
    • Between one and unlimited times +
  • End of line $
like image 171
Christian C. Salvadó Avatar answered Nov 03 '22 00:11

Christian C. Salvadó