3

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
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
cmob
  • 53
  • 1
  • 6

1 Answers1

7

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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Perfect! Used code Snippets, set to work everywhere, works perfect. Thank you :) – cmob Dec 25 '18 at 07:03
  • Hi, thanks. Help me please, in my shipping field (woocomerce) clients write in Hebrew, how allow only latin letter? I found function: public function validateLatin($string) { $result = false; if (preg_match("/^[\w\d\s.,-]*$/", $string)) { $result = true; } return $result; } but how use in your code? Thanks – user3331122 May 11 '20 at 06:11
  • @user3331122 Sorry I can't help on that subject… – LoicTheAztec May 11 '20 at 13:32