简体   繁体   中英

How to validate phone number in HTML form

I have a form and would like to see if the user filled the input with a correct number or not. The number must contains 10 digits and the two first digits should be equal to 05 or 06 . Can anyone help me how to do this in PHP or in JavaScript please?

According to comments and example phone number that you given, this code will validating number of digits and first two numbers of your country, i just replaced + with 0, for sure they won't enter plus.

$tel = '0512345678';

if(preg_match("/^0[5|6][0-9]{8}$/", $tel)) {
    echo "valid";
} else {
    echo "invalid";
}

Would you like to validate the phone number on the server or in the client (user's web browser)? In the first case you should use PHP, in the latter case a JavaScript function.

PHP:

function isValidPhoneNumber($number) {
  return preg_match('/^0[5|6][0-9]{8}$/', $number);
}

JavaScript:

function isValidPhoneNumber(number) {
  return /^0[5|6][0-9]{8}$/.test(number);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM