I have installed WooCommerce in my WordPress based website. Now my problem is when a customer checks out or creates an ID, then there is a field where the user can insert his phone number. That field accepts 9 numbers, so I want to apply a minimum length function on that field so the user will be prompted with an error message.
I have tried by adding these lines in 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; }
but this is not working and the strange thing is that when I use
['maxlength'] = 10;
it actually works.
Advertisement
Answer
By default WooCommerce checkout fields support the following attributes for the fields
$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' => '', );
You can add custom attributes by passing an array to 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; }
Which would produce the following HTML
<input type="text" minlength="12" value="" placeholder="" id="billing_phone" name="billing_phone" class="input-text ">
If minlength
doesn’t work ( and I have a suspicion that it probably won’t ) , try using the pattern
attribute
$fields['billing']['billing_phone']['custom_attributes'] = array( "pattern" => ".{12,}" ); //min 12 characters