Add CSS class with PHP for email validation

  php, woocommerce, wordpress

I am using this following code to add an email confirmation step to a Woocommerce checkout flow.

/**
 * Add "Confirm Email Address" Field At WooCommerce Checkout
 */

add_filter( 'woocommerce_checkout_fields' , 'silva_add_email_verification_field_checkout' );
   
function silva_add_email_verification_field_checkout( $fields ) {
  
$fields['billing']['billing_email']['class'] = array( 'form-row-wide' );
  
$fields['billing']['billing_em_ver'] = array(
    'label' => 'Confirm mail Address',
    'required' => true,
    'class' => array( 'form-row-wide' ),
    'clear' => true,
    'priority' => 999,
);
  
return $fields;
}

And this code to add an error, if they do not match.

/**
 * Generate error message if field values are different
 */
  
add_action('woocommerce_checkout_process', 'bbloomer_matching_email_addresses');
   
function bbloomer_matching_email_addresses() { 
    $email1 = $_POST['billing_email'];
    $email2 = $_POST['billing_em_ver'];
    if ( strtolower (trim($email2)) !== strtolower(trim($email1) )) {
        wc_add_notice( 'Your email addresses do not match', 'error' );
    }
}

However, I have the notices (for wc_add_notice) set to display:none; and rely on CSS classes to highlight the erroneous fields.

Is there a way to add a CSS class (.woocommerce-invalid) to ‘billing_em_ver’ if they do not match?

Edit: maybe even somethink like:

if ( strtolower (trim($email2)) !== strtolower(trim($email1) )) {
        ADD CSS CLASS INVALID
    }
else {
        ADD CSS CLASS VALIDATED
    }

Source: Ask PHP

LEAVE A COMMENT