Custom validation of WooCommerce checkout fields

后端 未结 4 1838
孤城傲影
孤城傲影 2021-01-02 09:41

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 requiremen

4条回答
  •  悲&欢浪女
    2021-01-02 10:34

    In your question you're saying that validation rule is not working and I guess it's written in a wrong way. You can test it in online with regexp tools, e.g. Regex101 or others.

    To answer more general on this topic, changing validation rules safely can be done this way:

    Make a copy of class-wc-validation.php to your theme directory in your_theme_path/woocommerce/includes/class-wc-validation.php and make customization to the validation rules.

    Then you should make a validation rule for the phone filed in checkout.js otherwise your field always will have green border despite it's invalid.

    So my solution was to add custom regular expression validator to checkout.js about line 192:

        if ( $parent.is( '.validate-phone' ) ) {
                if ( $this.val() ) {
    
                    var pattern = new RegExp(/^([0-9\s\/\+\-\#\_\(\)]*)$/);
    
                    if ( ! pattern.test( $this.val()  ) ) {
                        $parent.removeClass( 'woocommerce-validated' ).addClass( 'woocommerce-invalid woocommerce-invalid-phone' );
                        validated = false;
                    }
                }
            }
    

    And include your customized .js file (in functions.php)

    add_action( 'wp_enqueue_scripts', 'my_checkoutjs_enqueue_scripts', 100 );
    
    function gv_checkoutjs_enqueue_scripts() {
    
    if ( is_checkout() ) {
        wp_deregister_script( 'wc-checkout' );
        wp_enqueue_script( 'wc-checkout', get_template_directory_uri() . '/js/modified_checkout.js', array( 'jquery', 'woocommerce', 'wc-country-select', 'wc-address-i18n' ) );
    }}
    

    Hope this helps!

提交回复
热议问题