【问题标题】:Restrict a WooCommerce custom account number field value to be in numeric digits only将 WooCommerce 自定义帐号字段值限制为仅限数字
【发布时间】:2019-10-04 06:20:44
【问题描述】:

我在添加字段的代码方面得到了很大帮助,现在我希望发货/帐号只能是数字。

这是我当前的代码:

// login Field validation
add_filter( 'woocommerce_login_errors', 'account_login_field_validation', 10, 3 );
function account_login_field_validation( $errors, $username, $email ) {
    if ( isset( $_POST['billing_account_number'] ) && empty( $_POST['billing_account_number'] ) ) {
        $errors->add( 'billing_account_number_error', __( '<strong>Error</strong>: account number is required!', 'woocommerce' ) );
    }
    return $errors;
}

// Display field in admin user billing fields section
add_filter( 'woocommerce_customer_meta_fields', 'admin_user_custom_billing_field', 10, 1 );
function admin_user_custom_billing_field( $args ) {
    $args['billing']['fields']['billing_account_number'] = array(
        'label'         => __( 'Ship to/ Account number', 'woocommerce' ),
        'description'   => '',
        'custom_attributes'   => array('maxlength' => 6),
    );
    return $args;
}

感谢任何帮助。

【问题讨论】:

    标签: php wordpress validation woocommerce field


    【解决方案1】:

    您可以使用条件ctype_digit() 函数将值限制为数字:

    // login Field validation
    add_filter( 'woocommerce_login_errors', 'account_login_field_validation', 10, 3 );
    function account_login_field_validation( $errors, $username, $email ) {
        if ( isset( $_POST['billing_account_number'] ) && empty( $_POST['billing_account_number'] ) ) {
            $errors->add( 'billing_account_number_error', __( '<strong>Error</strong>: Account number is a required field.', 'woocommerce' ) );
        } elseif ( isset( $_POST['billing_account_number'] ) && ! ctype_digit($_POST['billing_account_number']) ) {
            $errors->add( 'billing_account_number_error', __( '<strong>Error</strong>: Only numeric digits are allowed on Account number field.', 'woocommerce' ) );
        }
        return $errors;
    }
    

    你也可以使用is_numeric()函数……

    相关: how to check if PHP variable contains non-numbers?

    【讨论】:

    • 嗨 Loic 非常感谢你每次都给了我很大的帮助,这也是你之前为我编辑的功能
    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 2013-07-07
    • 2015-12-16
    相关资源
    最近更新 更多