5

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

4 Answers 4

10

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 $
Sign up to request clarification or add additional context in comments.

1 Comment

yeah, the '+' sign is what i need
5

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

4 Comments

Could you explain what's the meaning of the two '+'?
I want to validate the zip input on every keyup event, not after all characters are entered.
Very neat script with /^\d{5,}$/.test($('#zip').val()) ? 'none' : 'inline'. Bravo
@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}$".
0
$('#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;
            }
     });

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.