Allow only letter on specific Woocommerce checkout fields

Viewed 2459

Trying to force Letters only (possibly also with non-English characters) in Woocommerce checkout field, First Name. we often have older customers so we need to control user input and prevent errors in advance.

What am I doing wrong?

NOTE: I'm aware of the Custom Validation thread Custom validation of WooCommerce checkout fields ... but it feels like this should be far simpler and specific solve?

Used Businessbloomers' code for forcing numbers only in Post Code field (works fine). SOURCE: https://businessbloomer.com/woocommerce-change-input-type-checkout-fields/

function bbloomer_change_checkout_field_input_type() {
echo "<script>document.getElementById('billing_postcode').type = 'number'; 
</script>";
}
add_action( 'woocommerce_after_checkout_form', 'bbloomer_change_checkout_field_input_type');

For Fname I changed type input to 'letter'.. but no result (still able to input numbers). Swapped 'type' for 'pattern', as below, but no luck.

function JBC_Force_letters_in_fname_field() {
echo "<script>document.getElementById('billing_first_name').pattern='[A- Za-z]';</script>";

}
add_action( 'woocommerce_after_checkout_form', 'JBC_Force_letters_in_fname_field');
  • Expecting: David
  • Getting/Allowing: Dav1D3
1 Answers

The following will remove numeric characters and some punctuation characters from billing and shipping first name and last name checkout fields and will handle also the postcode:

add_action( 'wp_footer', 'checkout_field_name_validator_script');
function checkout_field_name_validator_script() {
    // Only on checkout page
    if( ! ( is_checkout() && ! is_wc_endpoint_url() ) ) return;
    ?>
    <script>
    jQuery(function($){
        var b = '#billing_',    s = '#shipping_',   f = 'first_',   l = 'last_',
            n = 'name',         p = 'postcode',     c = ',';

        // Postcode fields
        $(b+p+c+s+p).bind('keyup blur',function(){
            $(this).val($(this).val().replace(/[^0-9]+/,''));
        });

        // First and Last name fields
        $(b+f+n+c+b+l+n+c+s+f+n+c+s+l+n).bind('keyup blur',function(){
            $(this).val($(this).val().replace(/[0-9.,;:?!]+/,''));
        });
    });
    </script>
    <?php
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Related