Check my work: gform_field_validation filter to prevent fake US phone numbers

Our contact form requires a working phone number, and the most common tactic to circumvent this is when people type in obvious fakes such as:

  • (000) 000-0000
  • (123) 456-7890

I want to use the gform_field_validation filter that Gravity Forms offers to check if the first three characters are 3 of the same number (with the exception of 888) or 123, but I’d like someone to check my work before I test it on my site:

add_filter( 'gform_field_validation', 'validate_phone', 10, 4 );

function validate_phone( $result, $value, $form, $field ) {

    $bad_area_code = "^\([0-7][0-7][0-7]\)|\(999\)|\(123\)";

    if ( $field->type == 'phone' && $field->phoneFormat != 'standard' && ! preg_match( $bad_area_code, $value ) && $value != '' ) {
        $result['is_valid'] = false;
        $result['message']  = 'Please enter a valid phone number.';
    }
  
    return $result;
}

It looks like your regex is going to still need some work to match against the proper values. This is a good tool for build regex patterns and running tests against it RegExr: Learn, Build, & Test RegEx

1 Like
© 2008 - 2021. Gravity Forms is a project by Rocketgenius Inc.