eMikkelsen
eMikkelsen

Reputation: 411

Force 8 digits in phone number WooCommerce

In Denmark all phone numbers are 8 digits. We'd like to force all orders to be 8 digits to prevent bugs and others with delivery. Never less, never more. When not 8 digits they should get a warning.

// You can add a custom placeholder to add a hint for your CUs what you expect
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields2' );

// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields2( $fields ) {

    $fields['billing']['billing_phone']['placeholder'] = 'Add 8 digits';

    return $fields;
}

/****************************************************************/
/* VALIDATION FOR PHONE FIELD THIS WILL THROW AN ERROR MESSAGE  */
/****************************************************************/

/**
 * Process the checkout
 **
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');

function my_custom_checkout_field_process() {
    global $woocommerce;

    // Check if set, if its not set add an error. This one is only requite for companies
    if ( ! (preg_match('/^[0-9]{8}$/D', $_POST['billing_phone'] ))){
        wc_add_notice( "Phone number must be 8 digits"  ,'error' );
    }
}

Unfortunately, it does not work. The number can still be anything.

Upvotes: 0

Views: 1417

Answers (1)

dale landry
dale landry

Reputation: 8610

Use strlen on your post. Then evaluate if it is equal to the length you want.

function my_custom_checkout_field_process() {
  global $woocommerce;

  // Check if set, if its not set add an error. This one is only requite for companies
  $len = strlen($_POST['billing_phone']); 
  if($len !== 8){     
    wc_add_notice( "Phone number must be 8 digits"  ,'error' );
  }
}

If you also want it to match number, use is_numeric() or !is_numeric()

$len = strlen($_POST['billing_phone']);   
if($len !== 8)){
  wc_add_notice( "Phone number must be 8 digits"  ,'error' );
  if(!is_numeric($_POST['billing_phone'])){           
    wc_add_notice( "Phone number must be number"  ,'error' );
  }
}

You can also set your input as type tel and add a pattern if there is specific pattern used in Denmark, this will help to format before submission on browsers that support html 5

<input type="tel" id="phone" name="phone" pattern="[0-9]{8}" required>

OUTPUT ERROR WHEN NUMBER LESS THAN 8:

enter image description here

OUTPUT ERROR WHEN MORE THAN 8:

enter image description here

OUTPUT ERROR WHEN NOT A NUMBER:

enter image description here

Upvotes: 1

Related Questions