Gravity Form Custom Validation in Phone Field (Regex)

PHOTO EMBED

Wed Jan 22 2025 20:24:21 GMT+0000 (Coordinated Universal Time)

Saved by @Muhammad_Waqar

// Custom function for validating phone numbers across multiple forms and fields
add_filter('gform_field_validation', function($result, $value, $form, $field) {

    $form_field_pairs = [
        4 => [8],
        1 => [4],
        2 => [4],
        3 => [4],
    ];

    if (isset($form_field_pairs[$form['id']]) && in_array($field->id, $form_field_pairs[$form['id']])) {
       
        $pattern = '/^\d{10}$/';
        
        if (!preg_match($pattern, $value)) {
            $result['is_valid'] = false;
            $result['message'] = 'Please enter a valid 10-digit phone number.';
        }
    }

    return $result;
}, 10, 4);
content_copyCOPY