Search code examples
phpregexvalidationpreg-matchvariable-length

Validate Australian DVA numbers (which may have variable length)


I'm doing validation on Australian DVA numbers, the rules are:

  1. String length should be 8 or 9
  2. First char should be N, V, Q, W, S or T
  3. The next part should be letters or space and can have up to 3 characters
  4. Next part should be number and can have up to 6 number
  5. If the string length is 9 then last char is a letter, if 8 then it must be a number // This is the tricky part

Here is my current attempt and it's working fine:

if (strlen($value) == 9 && preg_match("/^[NVQWST][A-Z\s]{1,3}[0-9]{1,6}[A-Z]$/", $value)) {
    return true;
}
if (strlen($value) == 8 && preg_match("/^[NVQWST][A-Z\s]{1,3}[0-9]{1,6}$/", $value)) {
    return true;
}
return false;

My question: Is there any way that I can combine these conditions in 1 regex check?


Solution

  • You can use

    ^(?=.{8,9}$)[NVQWST][A-Z\s]{1,3}[0-9]{1,6}(?:(?<=^.{8})[A-Z])?$
    

    See the regex demo.

    Details

    • ^ - start of a string
    • (?=.{8,9}$) - the string should contain 8 or 9 chars (other than line break chars, but the pattern won't match them)
    • [NVQWST] - N, V, Q, W, S or T
    • [A-Z\s]{1,3} - one, two or three uppercase letters or whitespace
    • [0-9]{1,6} - one to six digits
    • (?:(?<=^.{8})[A-Z])? - an optional occurrence of an uppercase ASCII letter if it is the ninth character in a string
    • $ - end of string.