Skip to content
Advertisement

How to set input pattern?

Can anyone please help me to set the correct input pattern for : when input starting digit is 2 then length is 17 digits if starts with 3 then length is 16 digits.

For example:

when input starts with number 2 then it must be: pattern="d{4} d{4} d{4} d{4} d{1}"

But when input starts with number 3 it must be: pattern="d{4} d{4} d{4} d{4}"

How to set pattern??

Advertisement

Answer

The most obvious solution is to use two alternatives:

^(?:2d{3} d{4} d{4} d{4} d|3d{3} d{4} d{4} d{4})$

See the regex demo.

The ^ matches the start of string, 2d{3} d{4} d{4} d{4} d matches the numbers starting with 2, 3d{3} d{4} d{4} d{4} matches the numbers starting with 3.

However, in PHP PCRE regex, you can use conditionals. Here, you may shorten the pattern to

^(?:(2)|3)d{3} d{4} d{4} d{4}(?(1) d)$

See this regex demo. Here, (?:(2)|3) matches and captures into Group 1 the 2 digit, or matches 3. The (?(1) d) pattern checks if Group 1 matched, and if it did, a space and a digit are required at the end of the string.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement