WooCommerce:强制执行最小长度 phone 数字字段

WooCommerce: Enforce minimum length phone number field

我已经在基于 WordPress 的网站中安装了 WooCommerce。现在我的问题是,当客户结账或创建 ID 时,会有一个字段,用户可以在其中插入他的 phone 号码。该字段接受 9 个数字,因此我想在该字段上应用最小长度函数,以便用户收到错误消息提示。

我尝试在 function.php 中添加这些行:

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields )
{        
     $fields['billing']['billing_phone']['minlength'] = 10;      
     return $fields;    
}

但这不起作用,奇怪的是当我使用

['maxlength'] = 10; 

它确实有效。

默认情况下,WooCommerce 结帐字段支持字段的以下属性

$defaults = array(
    'type'              => 'text',
    'label'             => '',
    'description'       => '',
    'placeholder'       => '',
    'maxlength'         => false,
    'required'          => false,
    'id'                => $key,
    'class'             => array(),
    'label_class'       => array(),
    'input_class'       => array(),
    'return'            => false,
    'options'           => array(),
    'custom_attributes' => array(),
    'validate'          => array(),
    'default'           => '',
);

您可以通过将数组传递给 custom_attributes

来添加自定义属性
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields )
{        
     $fields['billing']['billing_phone']['custom_attributes'] = array( "minlength" => "12" );      
     return $fields;    
}

这会产生以下结果 HTML

<input type="text" minlength="12" value="" placeholder="" id="billing_phone" name="billing_phone" class="input-text ">

如果 minlength 不起作用(我怀疑它可能不会起作用),请尝试使用 pattern 属性

$fields['billing']['billing_phone']['custom_attributes'] = array( "pattern" => ".{12,}" ); //min 12 characters

终于成功了。我将以下代码放入我的模板中:

$fields['billing']['billing_phone']['custom_attributes'] = array( "pattern" => ".{10,10}" );