Validating phone numbers in php
By Steve Suehring, Janet Valade Validating numbers in a web form can involve a regular expression, if you’re expecting a certain format or number of digits, or can involve math if you’re looking for certain values (or could be both too).ZIP code validation presents an easier case, so you tackle that first.The number must be checked for validity and length and then reformatted for display by later more detailed logic elements. After checking the input looks like a GB telephone number using the pattern above, the next step is to extract the NSN part so that it can be checked in greater detail for validity and then formatted in the right way for the applicable number range. If digits are all that’s found, then the next check can be run, to make sure the length is between 5 and 9 digits. If the phone field is set and not blank, then check to make sure it contains only digits.Next, the length is checked to make sure it’s at least ten digits.The regular expressions shown here are very similar to those found in the data files used by the open source libphonenumber project.
You could do this with a single regular expression, but doing so would prevent you from returning a specific error message: You wouldn’t know if users filled in letters or if they only had four digits in the ZIP field.Next, remove all punctuation and spaces from the remainder so that you're left with the 7, 9 or 10 digit National Significant Number. Use the regular expressions below to determine whether the remaining number is in a valid range, is the correct length for that range, what type of number it is and then how to correctly format it. You could also add a maximum length check here, but this one will account for international numbers, too. If it isn’t set (and you know that it’s required because you’re inside of a conditional test checking whether the phone number was set), then you return an error.
Assuming that it’s indeed set, check the value to make sure it’s one of the acceptable values for the field, similar to that done in the previous section for the state drop-down.
We will use the intl-tel-input plugin for that purpose.