fbpx

Strip or Validate the country code 1 from Gravity Forms phone field

Some submissions have incorrect phone numbers when using the standard US phone field format on Gravity Forms because the user’s saved phone number in their browser auto-fills the 1 prefix and is then missing the last digit.

Example issue: (134) 712-3456 instead of the correct number: (347) 123-4567
The script below adds a field validation to force a rule on any US Phone Number field so that does not allow a 1 or 0 to be the first number on any US phone field. The validation only runs after all other field validations pass and the submission tries to go through. The user will then get an error like this:

// force validation for US formatted phone number fields that they do not begin with 1 or 0
add_filter( 'gform_field_validation', function( $result, $value, $form, $field ) {

   if ( $field->type == 'phone' && $field->phoneFormat == 'standard' ) {
      
      if ( mb_substr( $value, 1, 1 ) == '0' || mb_substr( $value, 1, 1 ) == '1' ) {
         $result['is_valid'] = false;
         $result['message'] = 'Please check that you entered a valid phone number';
      }

   }

   return $result;

}, 10, 4 );
Shopping Cart