preg_match input validation exemption

59 Views Asked by At

I have a preg_match function and I want to block 'MT', but allow 'PMT'. How would I amend this to work as it's picking up the MT in PMT at the moment? Thanks!

function wppbc_custom_input_validation($message, $field, $request_data, $form_location) {
  if ($field['field'] == 'Input' && $field['meta-name'] == 'input_field') {
    $field_data = $request_data[$field['meta-name']];
    if (preg_match('/(MT|GT)(\d+)/i', $field_data) === 1) {
      return 'Not allowed.';
    }
    if (preg_match('/[A-Z]+\d+/i', $field_data) === 0) {
      return 'Invalid number'; 
    }
  }
  return $message;
}
1

There are 1 best solutions below

0
Vincent Decaux On

You can try to use this Regex:

((?<!P)MT|GT)(\d+)

(?<!P) is a negative lookbehind assertion that checks if 'MT' is not preceded by 'P'.

This way, 'MT' will only be matched if it is not preceded by 'P'. Therefore, 'PMT' will not be blocked, but 'MT' alone will be blocked.