Jump to content

phone validation code works strangely


parka

Recommended Posts

I can't seem to understand why my code doesn't work.

It's suppose to validate phone numbers with either 7 or 8 digits.

 

When run, it shows that numbers below 7 digits are invalid. That's what I wanted.

BUT, it all numbers above 8 digits as valid!

 

Any insights?

 

function isValidPhoneNo($in_phone){
if (ereg("[0-9]{7,8}", $in_phone) === false){
	print "$in_phone is invalid<br>";
} else {
	print "$in_phone is valid<br>";
}
}

$numbersArray = array(
1, 12, 123, 1234, 12345, 123456, 1234567, 12345678,
123456789, 1234567891, 12345678911, 123456789112
);
foreach ($numbersArray as $phoneNos){
isValidPhoneNo($phoneNos);
}

Link to comment
https://forums.phpfreaks.com/topic/41742-phone-validation-code-works-strangely/
Share on other sites

Another question. How should I validate for the area code for the phone numbers.

Here are the requirements:

- Must be 2 to 4 digits

- Parentheses surrounding the area code.

- Area code itself can be optional

E.g. (1234)22222222, (12)22222222, 22222222 should be valid.

 

I tried the following but didn't work.

function isValidPhoneNo($in_phone){
if (ereg("(\([0-9]{2,4}\))?^[0-9]{7,8}$", $in_phone) === false){
	print "$in_phone is invalid<br>";
} else {
	print "$in_phone is valid<br>";
}
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.