skip to Main Content

I’m writing this code. It’s working when I’m entering numbers or special characters. But Even after entering only Chars, it’s showing the same validation. Can anyone please help me out how to validate the First name & Last Name field characters ony?

add_action( 'woocommerce_after_checkout_validation', 'misha_validate_fname_lname', 10, 2);
 
function misha_validate_fname_lname( $fields, $errors ){
 
    if ( preg_match( '/^[a-zA-Z ]*$/', $fields[ 'billing_first_name' ] ) || preg_match( '/^[a-zA-Z ]*$/', $fields[ 'billing_last_name' ] )  ){
        $errors->add( 'validation', 'Only characters required' );
    }
}

2

Answers


  1. I think you want to allow only alphabets in name fields in that case you can use ctype_alpha() Function

    add_action( 'woocommerce_after_checkout_validation', 'validate_name', 10, 2);
     
    function validate_name( $fields, $errors ){
    
    $billing_first_name = $fields[ 'billing_first_name' ];
     
        if ( !ctype_alpha($billing_first_name)){
    
           wc_add_notice(__('Only alphabets are alowed in <strong>Billing First Name</strong>.'), 'error');
            
        }
    }
    

    Code goes in functions.php tested & works

    Login or Signup to reply.
  2. You can use the following code.

    add_action( 'woocommerce_after_checkout_validation', 'bks_validate_fname_lname', 10, 2);
    
    function bks_validate_fname_lname( $fields, $errors ){
        if (!preg_match( '/^[a-zA-Z ]+$/', $fields[ 'billing_first_name' ])){
            $errors->add( 'validation', 'First name should only have no special characters.' );
        }
        if (!preg_match( '/^[a-zA-Z ]+$/', $fields[ 'billing_last_name' ])){
            $errors->add( 'validation', 'Last name should only have no special characters.' );
        }
    }
    

    Few things worth noting

    1. As @CBroe said in the comment you should use + instead of * as it will check for empty submissions.
    2. You missed ! in your if condition.
    3. It’s better to inform the user exactly where is the issue, I have divided the code and checked for both of them seperately.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search