Custom validation of WooCommerce checkout fields
I have not seen your code that hooks these up to the woocommerce checkout flow.please check their documentation on
woocommerce_checkout_process
and woocommerce_checkout_order_processed
But in your case, I highly suggest that you hook it up on woocommerce_checkout_process
so put these codes below on your functions.php on your theme, or you create your own woocommerce plugins, and put it in the bootstrap code.
add_action('woocommerce_checkout_process', 'is_phone');function is_phone() { $phone_number = $_POST['---your-phone-field-name---']; // your function's body above, and if error, call this wc_add_notice wc_add_notice( __( 'Your phone number is wrong.' ), 'error' );}
Was facing the same issue and followed what others had said here, but Woocommerce only sets the errors on validation after woocommerce_checkout_process
hook.
But, in the latest Woocommerce 3.0 (not sure if this is in the 2.x version), we can use the woocommerce_after_checkout_validation
hook and then look into the $data
param if you are using the standard checkout fields or use $_POST
if you have custom fields that aren't added in the standard Woocommerce way. An example of the code is:
public function validate($data,$errors) { // Do your data processing here and in case of an // error add it to the errors array like: $errors->add( 'validation', __( 'Please input that correctly.' ));}add_action('woocommerce_after_checkout_validation', 'validate',10,2);
Hope that helps!
You should not edit plugin files, because if you update plugin all the customization will be lost, rather you can use hook to achieve your goal. You can use using
woocommerce_checkout_process
hook to do this.
Here is the code:
add_action('woocommerce_checkout_process', 'wh_phoneValidateCheckoutFields');function wh_phoneValidateCheckoutFields() { $billing_phone = filter_input(INPUT_POST, 'billing_phone'); if (strlen(trim(preg_replace('/^[6789]\d{9}$/', '', $billing_phone))) > 0) { wc_add_notice(__('Invalid <strong>Phone Number</strong>, please check your input.'), 'error'); }}
Code goes in functions.php
file of your active child theme (or theme). Or also in any plugin PHP files.
Please Note: By default WooCommerce use billing_phone
field to take phone number, but if you have customized it then you can replace billing_phone
with your field name.
Hope this helps!