views:

21

answers:

4

Hi, I am using following code to check first four characters are alphabate or not.

var pattern = new RegExp('^[A-Z]{4}');
if (enteredID.match(pattern))
    isValidAlphabates = true;
else {
    isValidAlphabates = false;

This is working fine; Now I need to check the next 6 characters (of the entered text) need to be only numeric (0 to 9).

I ve the option to use substring or substr method to extract that part & use the regular experssion: ^[0-9]{6}.

But is there a better way to do it, without using the substring method here.

+1  A: 

To clarify, the ^ means "at the start of the string". So you can combine your two regexes to say "start with four A-Z then have six 6 0-9."

var pattern = new RegExp('^[A-Z]{4}[0-9]{6}');
Jamiec
Thanks for the detailed explanation. :-)
Biki
+1  A: 

var pattern = new RegExp('^[A-Z]{4}[0-9]{6}');

Dan Grossman
+1  A: 
var pattern = new RegExp('^[A-Z]{4}[0-9]{6}$');

I added $ that means that checked string must end there.

Michał Niklas
Can u please let me know wats might go wrong if we wont use $, as I am not able to find any difference in my dev testing.
Biki
Without `$` it will match `ABCD123456abcdef`. You can test regexp (Python flavor, but in this simple example it does not matter) on: http://pythonregex.appspot.com/.
Michał Niklas
Ok, Then I think $ is not required for my regex. As my input has some more characters left after the above validation done. Wat is the significance of using +$, instead of only $?
Biki
'+' can be added to previous character/string to show that is there should be at least one such character/string. Look at JavaScript RegExp description: http://www.w3schools.com/jsref/jsref_obj_regexp.asp
Michał Niklas
+1  A: 

You can check the whole string at once

var pattern = new RegExp('^[A-Z]{4}[0-9]{6}');
Catharsis