How to Create WooCommerce Checkout Billing And Shipping Fields Validation

How to Create WooCommerce Checkout Billing And Shipping Fields Validation
73 Views

Phone number validation Checkout Page

<?php
add_filter( 'woocommerce_checkout_fields', 'cxc_checkout_billing_shipping_phone_no_validation' );
function cxc_checkout_billing_phone_no_validation( $fields ) {

	// billing phone number
	unset( $fields[ 'billing' ][ 'billing_phone' ][ 'validate' ] );
	// shipping phone number
	unset( $fields[ 'shipping' ][ 'shipping_phone' ][ 'validate' ] );
	
	// uncomment the following lines if you would like to make a phone field optional
	//unset( $fields[ 'billing' ][ 'billing_phone' ][ 'required' ] );
	//unset( $fields[ 'shipping' ][ 'shipping_phone' ][ 'required' ] );
	
	return $fields;
}
?>

ZIP code validation Checkout Page

<?php
add_filter( 'woocommerce_checkout_fields', 'cxc_checkout_billing_shipping_zip_no_validation' );
function cxc_checkout_billing_zip_no_validation( $fields ) {
	// billing postcode
	unset( $fields[ 'billing' ][ 'billing_postcode' ][ 'validate' ] );
	// shipping postcode
	unset( $fields[ 'shipping' ][ 'shipping_postcode' ][ 'validate' ] );
	
	return $fields;
}
?>

Email validation Checkout Page

<?php
add_filter( 'woocommerce_checkout_fields', 'cxc_checkout_billing_shipping_email_no_validation' );
function cxc_checkout_billing_shipping_email_no_validation( $fields ) {

	unset( $fields[ 'billing' ][ 'billing_email' ][ 'validate' ] );
	unset( $fields[ 'shipping' ][ 'shipping_email' ][ 'validate' ] );
	
	return $fields;
}
?>

Create Custom Validation Checkout Page

<?php
add_action( 'woocommerce_after_checkout_validation', 'cxc_checkout_billing_shipping_fname_lname_validation', 10, 2 );
function cxc_checkout_billing_shipping_fname_lname_validation( $fields, $errors ){	
	
	if ( preg_match( '/\\d/', $fields[ 'billing_first_name' ] ) || preg_match( '/\\d/', $fields[ 'billing_last_name' ] ) ){
		$errors->add( 'validation', 'Your first name or last name contains a number. Really?' );
	}
}
?>

JavaScript validation Checkout Page

<?php
add_action( 'wp_footer', 'cxc_checkout_billing_validation_jquery' ); 
function cxc_checkout_billing_validation_jquery(){
	if( ! is_checkout() ) { return; } 
  ?>
	<script type="text/javascript">
		jQuery(function($){
			jQuery( 'body' ).on( 'blur change', '#billing_last_name', function(){
				const wrapper = jQuery(this).closest( '.form-row' );
				// you do not have to removeClass() because Woo do it in checkout.js
				if( /\d/.test( $(this).val() ) ) { // check if contains numbers
					wrapper.addClass( 'woocommerce-invalid' ); // error
				} else {
					wrapper.addClass( 'woocommerce-validated' ); // success		
				}
			});
		});
	</script>
	<?php
}
?>

Was this article helpful?
YesNo

Leave a comment

Your email address will not be published.