WooCommerce:强制执行最小长度的电话号码字段

Was*_*yed 2 php regex validation wordpress woocommerce

我在基于WordPress的网站上安装了WooCommerce.现在我的问题是当客户签出或创建ID时,有一个字段,用户可以插入他的电话号码.该字段接受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;    
}
Run Code Online (Sandbox Code Playgroud)

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

['maxlength'] = 10; 
Run Code Online (Sandbox Code Playgroud)

它确实有效.

Ana*_*hah 7

默认情况下,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'           => '',
);
Run Code Online (Sandbox Code Playgroud)

您可以通过传递数组来添加自定义属性 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;    
}
Run Code Online (Sandbox Code Playgroud)

哪个会产生以下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