I'm doing validation on Australian DVA numbers, the rules are:
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?
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.