Reputation: 3068
I need to validate a username in Javascript where only the patterns below can pass:
Mine is currently using ^[A-Z]{3}[\- ]?[A-Z]{2}[\- ]?[0-9]{4}$
.
Are there any improvements to validate all above patterns in one string?
var v = document.getElementById('<%=txtCode.ClientID%>').value;
var patternForID = /^[A-Z]{3}[\- ]?[A-Z]{2}[\- ]?[0-9]{4}$/;
if (patternForID.test(v) == '') {
sender.innerHTML = "Please enter Valid Remeasurement Code";
args.IsValid = false; // field is empty
}
Upvotes: 0
Views: 114
Reputation: 405785
The following regular expression matches all three of your examples:
^([A-Z]{3}|[A-Z0-9]{4})-[A-Z]{2,3}-[0-9]{4,5}$
It's hard to tell exactly what your requirements are from those examples, but here's what the regex above matches.
([A-Z]{3}|[A-Z0-9]{4})
- Either three capital letters or any mix of 4 characters from capital letters and numbers.
[A-Z]{2,3}
- Two or three capital letters.
[0-9]{4,5}
- Four or five digits.
I assumed that -
was your only legal separator, so I made it a literal -
in the regex. If your separator really can be either a space or a -
, change it back to [- ]
. Also, adding a ?
after the separator makes it optional, which doesn't seem to fit your examples. Naturally, you need to put it back if the separators are optional.
See it work in RegexPal with your examples.
Upvotes: 1