parka Posted March 8, 2007 Share Posted March 8, 2007 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); } Quote Link to comment Share on other sites More sharing options...
effigy Posted March 8, 2007 Share Posted March 8, 2007 The expression works as long as it finds 7 to 8 digits anywhere in your string. You need to anchor your expression: ^[0-9]{7,8}$ Quote Link to comment Share on other sites More sharing options...
parka Posted March 9, 2007 Author Share Posted March 9, 2007 Thanks man Quote Link to comment Share on other sites More sharing options...
parka Posted March 9, 2007 Author Share Posted March 9, 2007 Error post. Quote Link to comment Share on other sites More sharing options...
parka Posted March 9, 2007 Author Share Posted March 9, 2007 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>"; } } Quote Link to comment Share on other sites More sharing options...
parka Posted March 9, 2007 Author Share Posted March 9, 2007 Solve, finally. ^(\([0-9]{2,4}\))?[0-9]{7,8}$ Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.