0

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.

4 Answers 4

1

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

Comments

1

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

Comments

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

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

4 Comments

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.
Without $ it will match ABCD123456abcdef. You can test regexp (Python flavor, but in this simple example it does not matter) on: pythonregex.appspot.com.
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 $?
'+' 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: w3schools.com/jsref/jsref_obj_regexp.asp
1

You can check the whole string at once

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

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.