-7

I would like to add a phone number in a registration form.

Users will need to input username, email, phone number and password. All these fields will be REQUIRED including the phone number.

I'm based in Kenya so I would like to limit the phone number to 13 characters including the + (sign).

The number should like: +25470164XXXX OR 070164XXXX both formats are acceptable.

Kindly assist me on how to implement this using preg_match function in PHP.

This is what I am currently using:

if (preg_match('/^(\+254|0)[1-9]\d{13}$/', $phone_number) ) {
    echo json_encode( array( 'success' => false, 'msg' => esc_html__('Invalid Phone Number (do not use letters, special characters or spaces)!', 'houzez-login-register') ) );
    wp_die();
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Amos
  • 151
  • 1
  • 2
  • 16

1 Answers1

3

Simple solution is:

preg_match('/^(\+254|0)\d{9}$/', $phone_number);

or maybe better

preg_match('/^(\+254|0)[1-9]\d{8}$/', $phone_number);

please apply more rules on your own.

  • Tried to help. You are right that the RE is suboptimal, there should be rules for the nine digits, [1-9]\d{8} or more complicated. – Jan Potužník Sep 05 '17 at 08:18