0

I need to validate two possible patterns for the input using HTML5 pattern.

  • 123456789a (first 9 digits should be exactly numbers and then an alphabetical character) nothing more nothing less

OR

  • 123456789012 (exactly 12 digits nothing more nothing less)

I tried ^([0-9]{12,12})|([0-9]{9,9}[A-Za-z]{1,1}), ^([0-9]{12})|([0-9]{9,9}[A-Za-z])$, and many more but the problem is if user enters an alphabet character when the total length is between 9 and 12, then it takes as a valid input. But it should be not.

Valid input is either 12 digits, or 9 digits with one char.

What have I done wrong?

2
  • Did you try putting the ^ and $ inside the brackets? Twice, for both patterns? Commented Jun 15, 2020 at 7:40
  • 1
    Or just replace )|( of the second pattern with |. The $ does not work for the first group in in your pattern. The problem is, that the | character either takes all from the left side or all from the right side, except if it is inside the brackets. Then, it just goes until the bracket boundary. In your case, it is outside the brackets though. So, it takes everything from left/right. Commented Jun 15, 2020 at 7:42

1 Answer 1

1

You could check for 9 digits at the start of the string: (see ^, beginning of input assertion, \d, digit character class and the x{n} quantifier)

^\d{9}

followed by either an alphabetical character or 3 more digits, and the end of the string: (see the non capturing group (?: ... ), [ ... ], the character set, x|y and $, end of input assertion)

(?:[a-zA-Z]|\d{3})$

So the expression would be:

^\d{9}(?:[a-zA-Z]|\d{3})$
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.