Reputation: 5815
I need to verify if a entered order number either is an original or a duplicate.
Order number can have either numbers or character and must be 13 ([A-Z0-9]{13})
A duplicate, its sepatated by a dash and its added a single capital letter ([-]{1}[A-Z]{1})
Given that the user can either enter the original or a duplicate order, the duplicate can be present or not, so, so far, I have this
([a-zA-Z0-9]{13})([-]{1}[A-Z]{1}){0,1}
It works correctly, but I'm having an issue validating that, when the duplicate is entered, its completed and correctly
/([a-zA-Z0-9]{13})([-]{1}[A-Z]{1}){0,1}/.test("ABCDEFGKLM123") // true
/([a-zA-Z0-9]{13})([-]{1}[A-Z]{1}){0,1}/.test("ABCDEFGKLM123-A") // true
/([a-zA-Z0-9]{13})([-]{1}[A-Z]{1}){0,1}/.test("ABCDEFGKLM123-AA") // true. Should return false!
/([a-zA-Z0-9]{13})([-]{1}[A-Z]{1}){0,1}/.test("ABCDEFGKLM123-") // true. Should return false!
/([a-zA-Z0-9]{13})([-]{1}[A-Z]{1}){0,1}/.test("ABCDEFGKLM123A") // true. Should return false!
I'm having problems getting this last 3 scenarios to be validated correctly
I'm still trying to figure out how to make that, if the optional part is present, its complete and correct over here https://regex101.com/r/wU4tQ5/3
Upvotes: 0
Views: 34
Reputation: 107287
There is some problem here.First you don't need {0,1}
for an optional case you can simply use ?
and [-]{1}
can be -
also [A-Z]{1}
to [A-Z]
.Also you need to use start and end anchors to match your string from start to end to refuse of matching some string like ABCDEFGKLM123-AA
^([a-zA-Z0-9]{13})(-[A-Z])?$
See demo https://regex101.com/r/kD2wN2/1
Upvotes: 3