As I understand your question, your logic is backwards. You want to accept it if the code is CL
, etc., not reject it. In other words, you should reject it only if the preg_match()
returns false. Just add a !
before the call to preg_match()
to reverse your if
condition, like so:
// Make sure designation code is valid
if (!preg_match("/(CL|CM|CP|CC|CBC|CRC)/",$designation)) { //notice the ! inside the parentheses
echo "<p class='error'>ERROR: Designation code not correct</p>";
$valid = false;
}
If I have misunderstood your requirements, please let me know.
Also, as others have pointed out, you can use the i
flag to avoid the call to strtoupper()
. If you want to accept only the codes you listed above and not, say, FCL
, add ^
and $
before and after the body of the regex, respectively. This also makes your strlen check unnecessary, unless you just want to show the error about the code length. This would make your entire code look like this:
// Make sure designation code is entered
if (empty($designation)) {
echo "<p class='error'>ERROR: Designation code is required</p>";
$valid = false;
}
// Make sure designation code is not too long (3 characters)
// NOTE: This block is now optional
if (strlen($designation)>3) {
echo "<p class='error'>ERROR: Designation code cannot be more than 3 characters</p>";
$valid = false;
}
// Make sure designation code is valid
if (!preg_match("/^(CL|CM|CP|CC|CBC|CRC)$/i",$designation)) { //notice the ! inside the parentheses
echo "<p class='error'>ERROR: Designation code not correct</p>";
$valid = false;
}