I want to build a regular expression which allows following cases:
- M1 1AA
- B33 8TH
- CR2 6XH
- DN55 1PT
- W1A 1HQ
- EC1A 1BB
and should not allow, only a single letter or a single number. E.g:
- A
- 2
- AA AAA
- 22 343
Also how do i call this in javascript. I am currently using the RegEx
^[A-Z0-9 ]*[A-Z0-9][A-Z0-9 ]*$
Which validates all the above cases includin a single letter or single number.
Please help me how to use a javascript to be called on a textbox change n validate using above regular expression
You’re close. One way to solve this problem would be
which allows arbitrary letter, number, or space (
[A-Z0-9 ]*) before, after, and between the letter and number, and allows either the letter to come first or the number to come first.However, there’s another way to solve this. You could use two regular expressions. First, check against the regular expression
which checks that you have only letters, numbers, and spaces. Then, check against the regular expression
which checks for at least one letter (
[A-Z]) and one number (\d), with both orders allowed. Note that this pattern doesn’t include the hat and dollar sign, so the letter and number can occur anywhere in the string.The two-regular-expression approach has the benefit of being easier to read and modify later.