tags:

views:

116

answers:

4

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');}
   }
 })
+3  A: 

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 $
CMS
yeah, the '+' sign is what i need
phil
+5  A: 

To answer your question, you use the Regexp constructor so that you can use a string for the pattern:

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

However, the code doesn't really make sense. As you change the style in each iteration in the loop, only the result of the last iteration will show up.

If you want to check that the value only contains digits and is at least five characters, you can just specify that in the pattern:

$('#zip').keyup(function(){
  $('#zip_error').css(
    'display',
    /^\d{5,}$/.test($('#zip').val()) ? 'none' : 'inline'
  );
})

Regular expression content:

^ = start of string
\d = same as [0-9]
{5,} = repeat five or more times
$ = end of string
Guffa
Could you explain what's the meaning of the two '+'?
phil
I want to validate the zip input on every keyup event, not after all characters are entered.
phil
this will do that, phil
Matt Ellen
Very neat script with /^\d{5,}$/.test($('#zip').val()) ? 'none' : 'inline'. Bravo
phil
@phil: The two pluses is just string concatenation. It concatenates `"^[0-9]{"`, the content of `i` and `"}$"`. If `i` contains 1, the result is `"^[0-9]{1}$"`.
Guffa
A: 
$('#zip').keyup( function(){ 
     var zip= $('#zip').val();
     var pattern = /^[0-9]+$/;
     if (zip.length >0 && zip.match(pattern)) {
                // write your code
                return true;
            }
          else {
                // write your code
                return false;
            }
     });
Space Cracker
A: 

Your for loop looks rather suspicious:

var i = $('#zip').val().length; for (i; i<=5; i++) {

}

Why do you start after the end of the string?

Don't you just want this?:

$('#zip').keyup(function() {  
    var pattern = /^[0-9]*$/;  
    if(!pattern.test($('#zip').val()))
        $('#zip_error').css('display','inline'); 
    else
        $('#zip_error').css('display','none');
})
Eric