This is the first part of the PHP Form validation tutorial. The second part is about validating email addresses with PHP.
The validation of data that has been entered in a form is necessary in most cases. Why is important?
For example, what good is holding a contest or sweepstakes if you can’t notify the winner because he or she entered an invalid telephone number or an incorrect address?
What good is having a mailing list if the e-mail addresses on it aren’t verified, and your mailing list just bounces back to you without reaching the subscribers and target audience?
Validating form entries saves you time and more importantly, it can save you money. And since somebody embossed the slogan “Time is money!”, this should be very important for your website!
Well, when should we validate? There are two types of validation; client side and server side.
For reference, client-side means that you are depending on what browser the user is currently using.
On the client side, validation is performed using JavaScript. And that can be very tricky because some users turn off JavaScript support in their browsers before they even come to your site.
If you encounter of one those users, client-side validation won’t help you much if you try to verify data from a form because your JavaScript code will not be executed or interpreted by the browser, which means you are back to square 1.
Remember, the winner of your competition entered the wrong address.
This is where server-side validation comes in handy. It will always work, no matter what.
Of course, assuming that you have access to the technology on your server. Server-side validation can be done with Perl, PHP, ASP, ColdFusion, JSP, and almost any other scripting language. For this tutorial, I’ll use PHP. A quite popular and easy-to-master server-side scripting language.
Now that you know the differences between client-side and server-side validation, you might ask, “Why use client-side validation at all?”
The reason is, that especially high-traffic websites, should seize the opportunity to take off the load of the server and distribute it to the client browser. This means that if you can verify the content of a field before it is submitted and processed by the server, it makes sense to do so.
And there is a user-friendly side to it as well. Since most people assume that once they have clicked the submit button on a form, the process is over. A nifty popup explaining what is missing or incorrect improves their chance of entering correct data into the form.
Who wants to miss out on that lottery jackpot just because he or she forgot to verify the data they entered on an online entry form?
Enough explanation, now let’s examine the code. We’ll start with server-side validation.
Server-side validation with PHP
For one of my last projects, I decided to use the following validation. I checked with JavaScript if anything was inserted in a field and then used server-side validation to figure out if the content was ok.
Let’s start with my favorite server-side validation. I am verifying a field for numbers only (e.g. a zip code), numbers and spaces (e.g. a telephone number), etc. Here’s my setup; I have a form.php and an error.php.
form.php
<html>
<head> ...</head>
<body>
<form action="error.php" method="post">
<table>
<tr>
<td>Your name:</td>
<td><input type="text" name="your_name"></td>
</tr>
<tr>
<td>Your phone:</td>
<td><input type="text" name="your_phone"></td>
</tr>
<tr>
<td>Zip code:</td>
<td><input type="text" name="your_zip"></td>
</tr>
</table><br>
<input type="submit">
</form>
</body>
</html>
Pretty easy, eh? The table is not necessary, but it helps to make the form look nice.
error.php
<?php extract($_POST); ?>
Now for the code explanation.
First of all, we have three functions to do the error checking. All three utilize a PHP function called preg_match. We call the function, tell it what field to check, and when the entered data matches the string it looks like it returns true, or false if it doesn’t.
If the function returns true it does nothing, if it returns false, it outputs the error message and increments the value of $error by 1. Now what does that do?
/[^a-zA-Z0-9\.\-\Ä\ä\Ö\ö\Ü\ü\ ]+$/
The slashes “/” and “/” are delimiters, “^” marks the start of the string or line, and the Dollar sign “$” the end of the string, or line.
The plus-symbol “+” means required. Knowing what the special characters mean, it says the following: A string, from start to finish, may contain these characters (a to z (lower case), A to Z (upper case), the numbers from 0 to 9, a dot (“.”), a given (“-“) and the special characters ä, ö ü (both upper and lower case) and space (” “)), and these characters only.
preg_match() is a case-sensitive function, which means it treats “a” and “A” differently. I included upper (“A-Z”) and lower case (“a-z”). So-called “special characters” (Special, because they have another meaning in PHP as well. But that’s another story.) have to be escaped, which means you write a backslash in front of it. For example: \- (the hiven) or \. (the dot). Other special characters are: ^[$()|*+?{\
.
The other two functions are self-explanatory, as they check only for numbers, and numbers and space (“\ “).
I hope you have learned the basics of server-side scripting. I’m adding the full example code below, feel free to use it on your websites and projects. If you have questions or need some help with using this code, leave your comment under the post.
function check_field1($field_name_1) {
if(!preg_match("/[^a-zA-Z0-9\.\-\Ä\ä\Ö\ö\Ü\ü\ ]+$/s",$field_name_1)) return TRUE; else return FALSE;
}
function check_field2($field_name_2) {
if(!preg_match("/[^0-9\ ]+$/",$field_name_2)) return TRUE; else return FALSE;
}
function check_field3($field_name_3) {
if(!preg_match("/[^0-9]+$/ ",$field_name_3)) return TRUE; else return FALSE;
}
/* Validation */
$error=0;
// check up variable
/* get it checking */
if(!check_field1($your_name)) {
echo "Illegal input $your_name in 'your_name'"; $error++; // $error=$error+1;
}
if(!check_field2($your_phone)) {
echo "Illegal input $your_phone in 'your_phone'"; $error++;
}
if(!check_field3($your_zip)) {
echo "Illegal input $your_zip in 'your_zip'"; $error++;
}
if($error == 0) {
echo " The data you entred was correct, thank you!<p> Your data:<br> Your name: $your_name<br> Your phone: $your_phone<br> ZIP code: $your_zip ";
}
else {
echo "Number of errors: $error";
}
17 Responses
The caret “^” in front of the open bracket means: “Not these characters”. It doesn’t indicate the start of the string. So, what it is really doing is checking if the input contains one or more characters that do not appear in the brackets. You have the bang “!” in front of preg_match, so the check is: “If the input doesn’t contain any characters that aren’t allowed, return true.”
Also, I think the proper way to match on spaces would be “\s”, not “\ “.
Very nice post!
very cool helped thank lol
Nice explination. Note what John Kline mentioned about the caret (^). It only indicates the front of a string when not in the context of brackets. Take a look at the following link for a good reference for regular expressions: regular-expressions.info
Erik
Thanks for the tutorial, but I’m having difficulty defining how to protect the non essential fields. I use mysql real escape string and I have white list validation for the essential fields.
For the non essential fields I’m not surehow you validate these especially as one of them is a menu.
My second question is how do you validate the message itself? Do you want to limit what somebody can enter? I thought about a string replace function but I couldn’t get it to work any help would be appreciated Thanks kevin
Kevin – you may want to post your questions in the forums (http://forums.htmlcenter.com/), as we would be better able to address your questions, there.
Regarding your first question, why can’t you validate a non-required field? You should be able to validate it the same way you validate the required fields. You just want to make sure that it doesn’t generate an error (or really even go through the validation process) if it’s empty.
I don’t quite understand your second question, though, which is why I recommend posting the question in the forums (and try rephrasing, please). Thank you, and I hope that helps.
Dude, it’s “hyphen”, not “hiven”!
What are the ways I can use to retain the data submitted via the form when the validation fails?
can you please help me? i have a problem. i want to validate numbers. i dont want any letter inputted. example:
contact number: hello
(CANNOT INPUT LETTERS! ONLY NUMBERS!)
thnk you
Hii
acutally on executing above i got parsing error as:
“Parse error: parse error in C:\wamp\www\Folder\error.php on line 65”
Please give a solution of it. i have checked the code. i have not found the problem..
I will look forward for your response..
have a nice day.!!
usually I use validation functionality described by Vitana here http://vitana-group.com/article/php/validation because it I can easy extend it. thanks vitana for help
Hi! My question is how can I use validation with Greek characters (Greek alphabet)?
for example instead of “^[a-z .’-]+$” I would like “^[α-ω .’-]+$” or “^[Α-Ω .’-]+$”
hey i am gettin a
Parse error: syntax error, unexpected $end in C:\xampp\htdocs\validate\error.php on line 67
error which is at the end of the page~!!!!
Plz help
That type of error usually means that a closing curly bracket (}) is missing somewhere at the end of one of your loops or if…else statements.
My code is giving an error message:
Could someone tell me what the heck is wrong.
Oops!
Guess their server didn’t like that!
Could it be that you are missing some ” {‘s and }’s ” in your “IF” structures above?
REVISED CODE:
==============
==============
Just a thought.
– Jim
I have seen many cases where syntax errors above could affect code below it ( just one of those pains-in-the-neck type of details! )