I need to validate a username in Javascript where only the patterns below can pass:
- ABC-DE-0001
- XEG-SS-21626
- FK1S-DAD-51345
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
}
-
Your third example won't pass.Blender– Blender2012年10月29日 02:41:35 +00:00Commented Oct 29, 2012 at 2:41
-
The second example won't pass either.Bill the Lizard– Bill the Lizard2012年10月29日 02:43:27 +00:00Commented Oct 29, 2012 at 2:43
-
Is white space a valid separator to replace the hyphen or is that just extra clutter in the regex?Fabrício Matté– Fabrício Matté2012年10月29日 02:47:53 +00:00Commented Oct 29, 2012 at 2:47
1 Answer 1
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.