1
votes

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'
        )
    );
}
1
Shouldn't you return $fields; at the end of the function?Spartacus
could you show me the proper place and syntax?arkitektron
Place return $fields before the final closing curly brace of the custom_override_checkout_fields function.Spartacus

1 Answers

1
votes

You can do this by validating checkout form submit at server side by using woocommerce_checkout_process hook, and PHP ctype_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 alowed in <strong>Billing First Name</strong>.'), 'error');
    }
    if (empty(trim($billing_last_name)) || !ctype_alpha($billing_last_name)) {
        wc_add_notice(__('Only alphabets are alowed in <strong>Billing Last Name</strong>.'), 'error');
    }
    // Check if Ship to a different address is set, if it's set then validate 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 alowed in <strong>Shipping First Name</strong>.'), 'error');
        }
        if (empty(trim($shipping_last_name)) || !ctype_alpha($shipping_last_name)) {
            wc_add_notice(__('Only alphabets are alowed 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!