Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom validation of WooCommerce checkout fields

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?

like image 208
Philomath Avatar asked Feb 19 '15 09:02

Philomath


1 Answers

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' );
}
like image 130
r4ccoon Avatar answered Oct 14 '22 23:10

r4ccoon