Home / Admin / How to Perform Field Comparisons Within Your WPForms
Duplicate Snippet

Embed Snippet on Your Site

How to Perform Field Comparisons Within Your WPForms

<10
Code Preview
php
<?php
/**
 * Perform Field Comparisons
 *
 * @link https://wpforms.com/developers/how-to-perform-field-comparisons-within-your-wpforms/
 */
 
function wpf_dev_compare_fields( $fields, $entry, $form_data ) {
     
    // Only run this snippet on the form ID 1000
    if ( absint( $form_data[ 'id' ] ) !== 1000 ) {
        return $fields;
    }
 
    // Enter the field ID for the first phone number
    $phone_1 = $fields[3][ 'value' ];
     
    // Enter the field ID for the second phone number
    $phone_2 = $fields[4][ 'value' ];
 
    // Regex pattern to match a simple 10-digit phone number
    $pattern = '/^\d{10}$/';
 
    // Now check if both phone numbers match the pattern
    if ( !preg_match( $pattern, $phone_1 ) || !preg_match( $pattern, $phone_2 ) || $phone_1 !== $phone_2 ) {
        wpforms()->process->errors[$form_data[ 'id' ]][ 'header' ] = esc_html__( 'Your phone number must be the same in both fields.', 'wpforms' );
    }
 
}
add_action( 'wpforms_process', 'wpf_dev_compare_fields', 10, 3 );

Comments

Add a Comment