I'm doing validation on Australian DVA numbers, the rules are:
- String length should be 8 or 9
- First char should be N, V, Q, W, S or T
- The next part should be letters or space and can have up to 3 characters
- Next part should be number and can have up to 6 number
- 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?
You can use
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,SorT[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.