Custom validation of WooCommerce checkout fields

checkout, php, validation, woocommerce, wordpress

Solution

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!

Problem

I would like add my own regular expression for validating the phone number. In my `class-wc-validation.php` I have changed the regular expression to my requirement. ``` public static function is_phone( $phone ) { //if ( strlen( trim( preg_replace( '/[\s\#0-9_\-\+\(\)]/', '', $phone ) ) ) > 0 ) if ( strlen( trim( preg_replace( '/^[6789]\d{9}$/', '', $phone ) ) ) > 0 ) return false; return true; } ``` But the validation is not happening. What am I missing?

Original source