Pass variable to regular expression pattern string in jquery

Posted by phil on Stack Overflow See other posts from Stack Overflow or by phil
Published on 2010-06-12T07:34:38Z Indexed on 2010/06/12 7:43 UTC
Read the original article Hit count: 1659

Filed under:

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');}
   }
 })

© Stack Overflow or respective owner

Related posts about jQuery