Hailwood Posted June 10, 2010 Share Posted June 10, 2010 Hi there ive been looking into preg_replace, how do i validate a phone number in the format of ^+[0-9]$ is the closest i can get it needs to begin with a + can have as many numbers as needed but thats it. Link to comment https://forums.phpfreaks.com/topic/204348-php-validate-phone-number/ Share on other sites More sharing options...
Pikachu2000 Posted June 10, 2010 Share Posted June 10, 2010 If they all, without fail, begin with a +, and contain a string of digits of no certain length, it would probably be easiest to just validate the form field as numeric, and concatenate the + to the string in the code. I.E., have the user enter the number (1234567890), then if(is_numeric($_POST['tel_no'])) { $tel_no = "+"; $tel_no .= $_POST['tel_no']; } Link to comment https://forums.phpfreaks.com/topic/204348-php-validate-phone-number/#findComment-1070210 Share on other sites More sharing options...
Daniel0 Posted June 10, 2010 Share Posted June 10, 2010 If they all, without fail, begin with a +, and contain a string of digits of no certain length, it would probably be easiest to just validate the form field as numeric, and concatenate the + to the string in the code. I.E., have the user enter the number (1234567890), then if(is_numeric($_POST['tel_no'])) { $tel_no = "+"; $tel_no .= $_POST['tel_no']; } So 1.234e56 is a valid phone number in your eyes? Link to comment https://forums.phpfreaks.com/topic/204348-php-validate-phone-number/#findComment-1070249 Share on other sites More sharing options...
Andy-H Posted June 10, 2010 Share Posted June 10, 2010 if (substr($_POST['tel_no'], 0, 1) == '+') { $num = substr($_POST['tel_no'], 1); } else { $num = $_POST['tel_no']; } if (!ctype_digit($num)) { echo $num . ' is not a valid telephone number.'; } else { $num = '+' . $num; //... } //edit missed a ; lol Link to comment https://forums.phpfreaks.com/topic/204348-php-validate-phone-number/#findComment-1070257 Share on other sites More sharing options...
Daniel0 Posted June 10, 2010 Share Posted June 10, 2010 For the sake of readability, I'd just use a regex in this case: if (!preg_match('#^\+\d+$#', $number)) { // it's invalid } Alternately: if ($number[0] != '+' || !ctype_digit(substr($number, 1))) { // it's invalid } Link to comment https://forums.phpfreaks.com/topic/204348-php-validate-phone-number/#findComment-1070261 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.