Validate Phone Number and Zip Code PHP - php

I am trying to validate a phone number and require it to have 10 digits only no spaces or special characters allowed (example: 0123456789) and the same goes with zip code except 5 digits only (example: 01234).
This is what I have for the phone number field so far.
$phone = stripslashes($_POST['phone']);
if(!$phone || $phone == "Phone Number*")
{
$error .= "Please enter your phone number.<br />";
}
The next if statement should retrieve an error similar to "Please enter a valid phone number. Example: "0123456789".

If you don't want to use regular expressions, take a look at ctype_digit
For example:
if(strlen($phone)==10 && ctype_digit($phone)) {
//valid
} else {
//invalid
}
I can't testify to whether this will be faster or slower than regular expressions, but I would reckon it's probably moot. It's more or less what makes the most sense to you.

You can try regex here:
if(preg_match('/^[0-9]{10}$/', $phone)){
// valid
}else{
// Not valid
}
Something a little like that will ensure only numerical characters and 10 of them. Just change the 10 to 5 for zip code.
One more thing if $_POST['phone'] is not set when you access it you will get a E_NOTICE so just a tip here for you do:
$phone = isset($_POST['phone']) ? stripslashes($_POST['phone']) : null;
if(!$phone) // ERROR

$phone = stripslashes($_POST['phone']);
if(!$phone || $phone == "Phone Number*")
{
$error .= "Please enter your phone number.<br />";
}
if(!preg_match('/^\d{10}$/', $phone)) $error .= "Please enter phone number as ##########.<br />";
And for zip code
if(!preg_match('/^\d{5}$/', $zip)) $error .= "Please enter your zip code as #####.<br />";
Keep in mind that this will not allow foreign zip codes (which may be of different lengths or include letters)
Just some other suggestions too (to prevent unnecessary error messages)
You may want to process your user input such that 123-456-7890 becomes 1234567890 by doing something like
preg_replace('/[^\d]/','',$input)
Maybe do a trim($input) to strip leading/trailing whitespace
Finally, is there any particular reason you are using stripslashes on $_POST['phone']?
If they are all digits like you expect, then this shouldnt be necessary.
If they aren't all digits, then you will throw an error regardless

how about:
function check($number,$length)
{
if(ctype_digit ($number) && strlen($number)==$length)
return true;
else
return false;
}
if(check("1234",4))
echo "ok";
else
echo "Please enter a valid phone number. Example: "0123456789";

Well, this an old post but I will throw in some comments here anyway.
1) you should really not force the user to put in the right numbers, of course your validation on the front end will cover this but never assume it to be case coming into the "backend" .
Consider the following instead of putting the on the user:
// remove chars
$number = preg_replace('/[\D]/', '', $number);
//unit test sanitizer
filter_var($number, FILTER_SANITIZE_NUMBER_INT)
// check number
preg_match('/^[0-9]{10}$/', $zip)
Example : Read in user input if enough digits entered in look up closest matching zipcode etc.. (I actually used this on a site once) Of course setting the frontend to check is useful, but in case that fails .
$number = 'z 02012s';
// remove chars
$number = preg_replace('/[\D]/', '', $number);
//unit test sanitizer
$number = filter_var($number, FILTER_SANITIZE_NUMBER_INT);
// check number
if (preg_match('#^[0-9]{5}$#', $number) === 1) {
//(optional) lookup closest zip using your DB.
$look_zip = $db->getClosestZipMatch($number);
} else {
echo $number . " isn't 5 digits only, do something.";
}

Related

Multiple conditions in one statement

I'm adding some very basic validation to a "name" form field. Generally, it's impossible to actually validate a name, but I figured I could at least verify that it's not empty, greater than maybe 2 characters (Al is the shortest name I can think of), and that those characters aren't just empty space.
Here's the conditionals I'm using:
// Check length of name field
if(!isset($name) || $name < 2 || (strlen($name) > 0 && strlen(trim($name)) == 0)) {
// Name field only spaces
if((strlen($name) > 0 && strlen(trim($name)) == 0) || trim($name) == '') {
$errors['name'] = "Please enter a real name...";
}
// Name too short
else {
$errors['name'] = "Are you sure <strong>".htmlspecialchars($name)."</strong> is your name?";
}
$msg_type = "error";
}
However, when I run this with a valid name, I get the "Name too short" error. I know it's got to be a problem with how I'm combining the conditionals, but I can't figure out where that problem lies.
$name < 2 doesn't work. You're trying to use strlen($name) < 2.
Well, there is a tool called regex which people have invented for string matching and it could be pretty conveniently used for validation cases like yours. If you want to validate a word let's say with at least 2 characters of length, you could do the following:
if(!preg_match('/\b\w{2,}/', $name)) {
$errors['name'] = "Are you sure <strong>".htmlspecialchars($name)."</strong> is your name?";
}
Where:
\b: word boundary
\w: word character
{2,}: two or more times for the word character

How best to validate a mobile phone number based on character length, starting with and numeric using php

Hi I have a mobile phone number field.
I am currently validating if empty:
<?php
if ($_REQUEST['text_message'] && !#$_REQUEST['text_message_mobile']){
$errors[] = "Please enter your mobile number for text messages";
}
?>
I would like to add validation to check that the mobile number is 11 characters long and begins with 07.
An example accepted phone number would be 07123456789
How best would I go about adding this validation using php?
Thanks for any help :o)
Take a look at type comparisions in PHP to look at how isset and empty responds with the variables you use.
Use strln to look at the length of the string, so you can know if the number is 11 characters long.
Use is_numeric to check if the variable contains only numbers, so you can avoid inputs like "07dsajdlsajdks".
Use substr to look at the first two characters of the string, so you can know if the number has 07 at the start.
This is how, more or less, should look at the end:
<?php
if(!isset($_REQUEST['text_message']) || empty($_REQUEST['text_message'])) {
//Here is null or undefined or an empty string
$errors[] = "Please enter your mobile number for text messages";
}
if(!is_numeric($_REQUEST['text_message'])) {
$errors[] = "Please provide a valid number";
}
if(strlen($_REQUEST['text_message']) !== 11) {
//Here is not 11 characters long
$errors[] = "Please provide 11 character number";
}
if(substr($_REQUEST['text_message'], 0, 2) !== "07") {
$errors[] = "Please provide number with 07 in the first two digits";
}
if(count($errors) > 0) {
echo "Resolve this errors: ";
print_r($errors);
}
else {
echo "You did everything perfect";
}
?>
You can do this with a regular expression :
$number = "0711111111111";
$pattern = "/^07[0-9]{9}$/";
echo preg_match($pattern, $number);
This expression will match any string starting with "07" and followed by exactly 9 numbers.
I dont know PHP but i can give solution with html and javaScript
here is a demo code :
<html>
<head>
<script>
function validate(){
var reg = new RegExp("^07[0-9]{9}$");
var mobile = document.getElementById("t1").value;
if(!reg.test(mobile))
{
alert("Invalid mobile number");
return false;
}
}
</script>
</head>
<body>
Mobile:<input id ="t1" type="text" maxlength = "11" />
<input type="button" value ="check" onclick="validate()" />
</body>
</html>
It uses Regular expression and checks with the test function
hope it helps.

Issues with integer operations

function sendSms($toPhone,$message){
$toPhone=intval(trim($toPhone));
if(strlen($toPhone)== 8 && $toPhone{0}==9){
//sending sms
}else{
return "error";
}
}
I am trying to validate mobile numbers for sending SMS. The first line trims the phone number string and then converts it to an integer. In the if statement, I want to make sure that the number length is 8 digits and it begins with 9. This function always goes for the else even if the number is correct( 8 digits and begins with 9). What could be the issue here.
Why not regex?
$valid = preg_match('/^9[0-9]{7}$/', trim($phone));
You can remove from $toPhone all not digits
function sendSms($toPhone,$message){
$_phone = '';
for ($i = 0; $i < strlen($toPhone); $i++)
{
if (is_numeric($toPhone[$i]))
$_phone .= $toPhone[$i];
}
if(strlen($_phone)== 8 && $_phone[0]=='9'){
//sending sms
}else{
return "error";
}
}
After you converted the phone number to an integer with $toPhone=intval(trim($toPhone));,, you can't access the digits in the way you are trying with $toPhone{0}, because you operate on a number and not on a string any more.
See this isolated example:
$number = 987654321;
var_dump($number{0}); //NULL
However, substr would be capable of doing this:
$number = 987654321;
var_dump(substr($number, 0, 1)); //string(1) "9"
Converting a whole number to integer isn't a good idea anyways, because users might enter the number with spaces in between or signs like + and /. Better search for an already existing approach to validate phone numbers.
Take a look here, where the topic "validate mobile phone numbers" is covered in more detail: A comprehensive regex for phone number validation
You convert variable to integer and apparently $toPhone[0] works on strings only.
The same function without intval() works as you wanted.
function sendSms($toPhone, $message)
{
$toPhone = trim($toPhone);
if(strlen($toPhone) == 8 && $toPhone[0] == 9){
//sending sms
} else {
return "error";
}
}

Numeric input validation in PHP

I'm trying to validate an input for Account number in php form. It should contain 8 numbers and '-' optionally. If there is '-' - it should be ignored.
After pressing the Submit button, the warning message suppose to be displayed above the form in case input is invalid.
Please help.
This is what I got so far, but I'm not sure if this is correct and don't know how to display a warning message above the form.
$acctnum= "$acctnum";
if(empty($acctnum)){
echo "You did not enter an account number, please re-enter"; }
else if(!preg_match("\-^[0-9]{8}", $acctnum)){
echo "Your account number can only contain eight numbers. Please re-enter."; }
Thank you!
You don't appear to be trying. No documentation or tutorial will tell you to make a Regex like that. For starters, where are the delimiters? Why is - escaped when it's outside a character class and therefore has no special meaning? What is that ^ doing there?
This should do it:
$acctnum = str_replace("-","",$acctnum);
if( !preg_match("/^\d{8}$/",$acctnum)) echo "Error...";
Since regex are quite expensive I'd go like that instead:
$acctnum = (int) $acctnum; // this automatically ignore the '-'
if ($acctnum < 0) $acctnum = -$acctnum;
$digits = ($acctnum == 0) ? log10($acctnum) + 1 : 1;
if ($digits === 8) { ... }
Split the task in two. First get rid of the "-" with str_replace and then check for the numbers.
$match = preg_match("/^\d{8}$/", str_replace("_", "", $str));
if ($match > 0) {
// Correct
} else {
// incorrect
}

looking to validate US phone number w/ area code

I'm working on a function to validate a US phone number submitted by a user, which can be submitted in any of the popular number formats people usually use. My code so far is as follows:
$number = '123-456-7890';
function validate_telephone_number($number) {
$formats = array(
'###-###-####',
'(###)###-###',
'(###) ###-###',
'##########'
);
$number = trim(preg_replace('[0-9]', '#', $number));
if (in_array($number, $formats)) {
return true;
} else {
return false;
}
}
First off, this code does not seem to be working, and returns false on all submitted numbers. I can't seem to find my error.
Secondly, I'm looking for an easy way to only allow phone numbers from an array of specific allowed area codes. Any ideas?
For your first question:
preg_replace('/[0-9]/', '#', $number)
or '/\d/'
For the second question this may help you:
$areaCode = substr(preg_replace('/[^\d]/', '', $number),0 , 3);
This will give you the first 3 digits in the number by discarding all other characters.
I'm not familiar with the US area codes format so I cannot help you more with this one.
Bonus:
if (in_array($number, $formats)) {
return true;
} else {
return false;
}
is equivalent to
return in_array($number, $formats);
As a matter of fact any statement of the form
if(<expression>){
return true;
}
else{
return false;
}
can be written as return (bool) <expr>;, but in this case in_array will always return a Boolean so (bool) is not needed.
Your code does not check for well formatted but invalid numbers - for example, no area code starts with 0 or 1 in the US, so this could be checked. Also, your formats do not allow for country code inclusion - +15551234567 would be rejected, for example.
If you don't care about the formatting and just want to validate if the digits in the input amount to a valid US phone number, you could use something like this:
$clean_number = preg_replace("/[^0-9]/", '', $number);
$valid = preg_match("/^(\+?1)?[2-9][0-9]{9}$/", $clean_number);
Of course, this will also accept "foo 5555555555 bar" as a valid number - if you want to disallow that, make the preg_replace more restrictive (e.g, remove only brackets, spaces and dashes).
If you prefer to do this without maintaining a lot of code, you an check out this API that validates a US number and provides several formats for the number https://www.mashape.com/parsify/format
Look here for a code project that has a function for validating phone numbers.

Categories