php WooCommerce 结帐字段的自定义验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28603144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:58:26  来源:igfitidea点击:

Custom validation of WooCommerce checkout fields

phpwordpressvalidationwoocommercecheckout

提问by Philomath

I would like add my own regular expression for validating the phone number. In my class-wc-validation.phpI have changed the regular expression to my requirement.

我想添加我自己的正则表达式来验证电话号码。在我中,class-wc-validation.php我已将正则表达式更改为我的要求。

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?

但是验证没有发生。我错过了什么?

回答by r4ccoon

I have not seen your code that hooks these up to the woocommerce checkout flow. please check their documentation on

我还没有看到您的代码将这些与 woocommerce 结帐流程挂钩。请检查他们的文档

woocommerce_checkout_processand woocommerce_checkout_order_processed

woocommerce_checkout_processwoocommerce_checkout_order_processed

But in your case, I highly suggest that you hook it up on woocommerce_checkout_process

但在你的情况下,我强烈建议你把它连接起来 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.

所以把这些代码放在你主题的functions.php下面,或者你创建自己的woocommerce插件,然后把它放在引导代码中。

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' );
}

回答by shivaramanaiyer

Was facing the same issue and followed what others had said here, but Woocommerce only sets the errors on validation after woocommerce_checkout_processhook.

面临同样的问题并遵循其他人在此处所说的内容,但 Woocommerce 仅在woocommerce_checkout_process挂钩后设置验证错误。

But, in the latest Woocommerce 3.0 (not sure if this is in the 2.x version), we can use the woocommerce_after_checkout_validationhook and then look into the $dataparam if you are using the standard checkout fields or use $_POSTif you have custom fields that aren't added in the standard Woocommerce way. An example of the code is:

但是,在最新的 Woocommerce 3.0(不确定这是否在 2.x 版本中)中,如果您使用的是标准结帐字段,我们可以使用woocommerce_after_checkout_validation钩子然后查看$data参数,或者$_POST如果您有自定义字段,则使用t 以标准的 Woocommerce 方式添加。代码示例如下:

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!

希望有帮助!

回答by Raunak Gupta

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_processhook to do this.

你不应该编辑插件文件,因为如果你更新插件,所有的自定义都会丢失,而你可以使用钩子来实现你的目标。您可以使用 using woocommerce_checkout_processhook 来执行此操作。

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.phpfile of your active child theme (or theme). Or also in any plugin PHP files.

代码位于functions.php活动子主题(或主题)的文件中。或者也可以在任何插件 PHP 文件中。

Please Note: By default WooCommerce use billing_phonefield to take phone number, but if you have customized it then you can replace billing_phonewith your field name.

请注意:默认情况下,WooCommerce 使用billing_phone字段来获取电话号码,但如果您已经自定义了它,那么您可以替换billing_phone为您的字段名称。

Hope this helps!

希望这可以帮助!

回答by Arkady

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. Regex101or others.

在您的问题中,您是说验证规则不起作用,我猜它以错误的方式编写。您可以使用 regexp 工具在线测试它,例如Regex101或其他工具。

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

要回答有关此主题的更一般性问题,可以通过以下方式安全地更改验证规则:

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

复制class-wc-validation.php到您的主题目录中your_theme_path/woocommerce/includes/class-wc-validation.php,并对验证规则进行自定义。

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

然后,您应该为提交的电话制定验证规则,checkout.js否则尽管无效,您的字段始终会有绿色边框。

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

所以我的解决方案是将自定义正则表达式验证器添加到checkout.js大约第 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)

并包含您自定义的 .js 文件(在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!

希望这可以帮助!