问题描述
我在 WooCommerce 结帐表单中为电话号码添加了一个新字段。
除了 maxlength = "10" 之外,一切正常。添加代码段后,当我检查元素时显示 maxlength = 10,但电话字段允许我输入 n 个字符。
我做错了什么吗?
这是我在 functions.PHP
add_action('woocommerce_after_checkout_billing_form','custom_checkout_field');
function custom_checkout_field($checkout)
{
woocommerce_form_field('billing_phone_2',array(
'type' => 'number','maxlength' => "10",'id' => 'billing_phone_2','class' => array(
'input-text form-row-wide'
),'required' => 'required' === get_option( 'woocommerce_checkout_phone_field','required' ),'label' => __('Phone 2'),'placeholder' => __(''),),$checkout->get_value('billing_phone_2'));
}
解决方法
对于type
,您可以使用tel
,对于maxlength
,不需要将数字放在引号之间
所以你得到:
// Display a custom checkout field after billing form
function action_woocommerce_after_checkout_billing_form( $checkout ) {
woocommerce_form_field( 'billing_phone_2',array(
'type' => 'tel','maxlength' => 10,'class' => array( 'form-row-wide' ),'required' => true,'label' => __( 'Phone 2','woocommerce' ),'placeholder' => __( 'My placeholder',),$checkout->get_value( 'billing_phone_2' ));
}
add_action( 'woocommerce_after_checkout_billing_form','action_woocommerce_after_checkout_billing_form',10,1 );
可选:对自定义(必填)字段进行一些验证
// Custom checkout field validation
function action_woocommerce_checkout_process() {
// Isset
if ( isset( $_POST['billing_phone_2'] ) ) {
$domain = 'woocommerce';
$phone = $_POST['billing_phone_2'];
// Empty
if ( empty ( $phone ) ) {
wc_add_notice( __( 'Please enter a phone number to complete this order',$domain ),'error' );
}
// Validates a phone number using a regular expression.
if ( 0 < strlen( trim( preg_replace( '/[\s\#0-9_\-\+\/\(\)\.]/','',$phone ) ) ) ) {
wc_add_notice( __( 'Please enter a valid phone number','error' );
}
}
}
add_action( 'woocommerce_checkout_process','action_woocommerce_checkout_process',0 );
如果 type
= number
,则可以使用 min
和 max
属性
// Display a custom checkout field after billing form
function action_woocommerce_after_checkout_billing_form( $checkout ) {
woocommerce_form_field( 'billing_phone_2',array(
'type' => 'number','custom_attributes' => array(
'min' => 0,'max' => 9999999999,'placeholder' => __( 'Phone 2',1 );
虽然我不建议将其用于电话号码,但存在类型“tel”是有原因的,正如在 WooCommerce 中的其他电话字段中所使用的