Phone Validation - Any improvements that can be made?

Hi,

I’m sure plenty of you run into submissions from fake users / users that don’t want to give real details / users that make mistakes…

I’ve worked on creating some some code using the gform_validation hook to try and limit/remove some of these and I’ve come up with the following code that should work, but I’m looking to see if anyone has anything better or can provide any comments about my code where they believe it can be improved.

The code should throw validation warnings for numbers that:

  • Are shorter than 5 digits (Allows small island country numbers)
  • Are longer than 15 digits (International Telecommunication Union’s regulation max)
  • Are the same number all the way through like 111111111
  • Are sequential ascending/descending like 123456789
  • Have obvious sequential patterns like 123123123 or 121212121
add_filter('gform_validation', 'validate_phone_numbers');
function validate_phone_numbers($validation_result) {
    $form = $validation_result['form'];

    foreach ($form['fields'] as &$field) {
        // Check if the field is a phone field
        if ($field->type == 'phone') {
            $phone_number = rgpost("input_{$field->id}");

            if (!isValidPhoneNumber($phone_number)) {
                $validation_result['is_valid'] = false;
                $field->failed_validation = true;
                $field->validation_message = 'Please enter a valid phone number.';
            }
        }
    }

    $validation_result['form'] = $form;
    return $validation_result;
}

function isValidPhoneNumber($number) {
    // Check the length of the phone number
    $strippedNumber = preg_replace('/\D/', '', $number); // Remove non-digits
    $length = strlen($strippedNumber);
    if ($length < 5 || $length > 15) {
        return false;
    }

    // Basic phone number validation
    if (!preg_match('/^[+]?[(]?[0-9]{1,4}[)]?[-\s./0-9]*$/', $number)) {
        return false;
    }

    // Check for repeated or sequential digits
    if (preg_match('/^(.)\1+$/', str_replace(['+', '(', ')', '-', ' ', '.'], '', $number))) {
        return false;
    }

    // Check for sequential ascending or descending numbers
    if (isSequential($strippedNumber)) {
        return false;
    }

    return true;
}

function isSequential($number) {
    $length = strlen($number);
    for ($i = 0; $i < $length - 1; $i++) {
        if (abs($number[$i] - $number[$i + 1]) != 1) {
            return false;
        }
    }
    return true;
}

I believe I’ve covered every major validation issue… looking forward to some comments!

Thanks

To simplify the code, you could use the gform_field_validation filter instead. This eliminates the need for looping through the form fields and setting the form validation result.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.