Home > Enterprise >  Regex to validate the input rules
Regex to validate the input rules

Time:09-02

I want to validate using regex the user input to see if match the following rules.

Valid input:

2-000000000000
1-234342324342
...

Rules:

  1. It has to be 13 digit numbers, no string.
  2. Allow hyphen - come after the first character.
  3. Allow space before and after the hyphen - character.

Here's what I tried in PHP, but still not correct:

if(preg_match("/[0-9?\-[0-9]/i])) {

  echo "matched";

} 

CodePudding user response:

Note your double-quoted string literal is malformed, the closing " is missing.

Also, mind that [0-9?\-[0-9] is a malformed regex that matches a digit, ?, - or [ char. The i flag is irrelevant here, since there are no letters in the pattern.

I suggest using

preg_match("/^\d *- *\d{12}\z/", $string)

If the spaces can be any whitespace, replace the literal spaces with \s.

Note the use of \z anchor, I prefer it to $ in validation scenarios, since $ can match before the final line feed char in the string.

See the regex demo (\z replaced with $ since the input is a single multiline string there).

  • Related