0

I need to validate a username in Javascript where only the patterns below can pass:

  1. ABC-DE-0001
  2. XEG-SS-21626
  3. 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
}
dda
6,2212 gold badges28 silver badges37 bronze badges
asked Oct 29, 2012 at 2:39
3
  • Your third example won't pass. Commented Oct 29, 2012 at 2:41
  • The second example won't pass either. Commented 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? Commented Oct 29, 2012 at 2:47

1 Answer 1

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.

answered Oct 29, 2012 at 2:48
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.