I would like to add custom validation to the phone number in checkout page of woocommerce. How do I do this??
BY default woocommerce already have regular expression validation. The easiest way would be to validate it through jquery.
EDIT: Try not to make any changes to the woocommerce core as they will be over ridden on next update. Try this code
// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
$fields['shipping']['shipping_phone'] = array(
'label' => __('Phone', 'woocommerce'),
'placeholder' => _x('Phone', 'placeholder', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
In my opinion there's no need to override default Woocommerce fields, nor use Javascript validation.
You can add a custom validation, that will be added to the Woocommerce's default billing phone field validation, hooking to an action triggered after submitting checkout.
This is the code I just implemented for a client.
// Custom validation for Billing Phone checkout field
add_action('woocommerce_checkout_process', 'custom_validate_billing_phone');
function custom_validate_billing_phone() {
$is_correct = preg_match('/^[0-9]{6,20}$/', $_POST['billing_phone']);
if ( $_POST['billing_phone'] && !$is_correct) {
wc_add_notice( __( 'The Phone field should be <strong>between 6 and 20 digits</strong>.' ), 'error' );
}
}
Of course, instead of my preg_match
you can check anything else and adjust your conditional code to your needs.
You can also add custom validation for other default fields, by checking on the right $_POST
variable, or your own custom checkout fields, after you correctly set them up, of course, but this is another topic :)
Hope this helps.