How can I restrict only alphabet characters in the billing first name, billing last name, shipping first name and shipping last name in WooCommerce checkout?
I am trying the following in the my Child Theme's functions.php file and it is causing the checkout section to not appear when I go to checkout in WooCommerce. Please advise.
add_filter('woocommerce_checkout_fields', 'custom_override_checkout_fields');
function custom_override_checkout_fields($fields) {
$fields['billing']['billing_first_name'] = array(
'label' => __('First name', 'woocommerce'),
'placeholder' => _x('First name', 'placeholder', 'woocommerce'),
'required' => false,
'clear' => false,
'type' => 'text',
'class' => array(
'alpha'
)
);
}
You can do this by validating checkout form submit at server side by using
woocommerce_checkout_process
hook, and PHPctype_alpha()
function.
Here is the code:
add_action('woocommerce_checkout_process', 'wh_alphaCheckCheckoutFields');
function wh_alphaCheckCheckoutFields() {
$billing_first_name = filter_input(INPUT_POST, 'billing_first_name');
$billing_last_name = filter_input(INPUT_POST, 'billing_last_name');
$shipping_first_name = filter_input(INPUT_POST, 'shipping_first_name');
$shipping_last_name = filter_input(INPUT_POST, 'shipping_last_name');
$ship_to_different_address = filter_input(INPUT_POST, 'ship_to_different_address');
if (empty(trim($billing_first_name)) || !ctype_alpha($billing_first_name)) {
wc_add_notice(__('Only alphabets are allowed in <strong>Billing First Name</strong>.'), 'error');
}
if (empty(trim($billing_last_name)) || !ctype_alpha($billing_last_name)) {
wc_add_notice(__('Only alphabets are allowed in <strong>Billing Last Name</strong>.'), 'error');
}
// If the ‘Ship to a different address’ option is selected, validate the shipping fields.
if (!empty($ship_to_different_address)) {
if (empty(trim($shipping_first_name)) || !ctype_alpha($shipping_first_name)) {
wc_add_notice(__('Only alphabets are allowed in <strong>Shipping First Name</strong>.'), 'error');
}
if (empty(trim($shipping_last_name)) || !ctype_alpha($shipping_last_name)) {
wc_add_notice(__('Only alphabets are allowed in <strong>Shipping Last Name</strong>.'), 'error');
}
}
}
Code goes in functions.php
file of your active child theme (or theme). Or also in any plugin PHP files.
Code is tested and works.
Hope this helps!