We have already explain about form validation using javascript and jQuery, but this time we will show you how to validate your form using PHP.
Very first we have to create a form in html setting action “#” and method “POST” with some fields, when a user clicks on submit button all the data starts travel in URL but it will be hidden, as we set method = “POST”.
Now, on page refresh, PHP code runs, all values fetches from URL into PHP variables and aplying “preg_match ( )“ function on them.
PHP Code segment from validation.php
<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$websiteError ="";
// On submitting form below function will execute.
if(isset($_POST['submit'])){
if (empty($_POST["name"])) {
$nameError = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameError = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailError = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([w-]+@[w-]+.[w-]+)/",$email)) {
$emailError = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check address syntax is valid or not(this regular expression also allows dashes in the URL)
if (!preg_match("/b(?:(?:https?|ftp)://|www.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i",$website)) {
$websiteError = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderError = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//php code ends here
?>
HTML Code segment from “validation.php”
<!DOCTYPE html>
<html>
<head>
<title>Form Validation with PHP - Demo Preview</title>
<meta content="noindex, nofollow" name="robots">
<link href="style.css" rel="stylesheet">
</head>
<body>
<div class="maindiv">
<div class="form_div">
<div class="title">
<h2>Form Validation with PHP.</h2>
</div>
<form action="validation.php" method="post">
<h2>Form</h2>
<span class="error">* required field.</span>
Name:
<input class="input" name="name" type="text" value="">
<span class="error">* <?php echo $nameError;?></span>
E-mail:
<input class="input" name="email" type="text" value="">
<span class="error">* <?php echo $emailError;?></span>
Gender:
<input class="radio" name="gender" type="radio" value="female">Female
<input class="radio" name="gender" type="radio" value="male">Male
<span class="error">*<?php echo $genderError;?></span>
Website:
<input class="input" name="website" type="text" value="">
<span class="error"><?php echo $websiteError;?></span>
Comment:
<textarea cols="40" name="comment" rows="5">
</textarea>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
</div>
</body>
</html>
CSS File : style.css
@import "http://fonts.googleapis.com/css?family=Droid+Serif";
/* Above line is to import Google font style */
.maindiv{
margin:0 auto;
width:980px;
height:500px;
background:#fff;
padding-top:20px;
font-size:14px
}
.title{
width:500px;
height:70px;
text-shadow:2px 2px 2px #cfcfcf;
font-size:16px;
text-align:center;
font-family:'Droid Serif',serif
}
.form_div{
width:70%;
float:left
}
form{
width:440px;
border:1px dashed #ccc;
padding:10px 30px 40px;
background-color:#f0f8ff;
font-family:'Droid Serif',serif
}
form h2{
text-align:center;
text-shadow:2px 2px 2px #cfcfcf
}
textarea{
width:250px;
height:60px;
border-radius:1px;
box-shadow:0 0 1px 2px #123456;
margin-top:10px;
padding:5px;
border:none
}
.input{
width:250px;
height:15px;
border-radius:1px;
box-shadow:0 0 1px 2px #123456;
margin-top:10px;
padding:5px;
border:none;
margin-bottom:20px
}
.submit{
color:#fff;
border-radius:3px;
background:#1F8DD6;
padding:5px;
margin-top:40px;
border:none;
width:100px;
height:30px;
box-shadow:0 0 1px 2px #123456;
font-size:16px
}
.error{
color:red
}
.radio{
width:15px;
height:15px;
border-radius:1px;
margin-top:10px;
padding:5px;
border:none;
margin-bottom:20px
}
.formget{
float:right;
margin-top:85px
}
Conclusion:
Validation is very important aspect in data submission, hence we told you all the three methods to validate your form. keep learning our next posts.
32 Replies to “Form Validation Using PHP”
Hii, Ram. It feels great you like the post. Thank you so much
Keep reading our blogs….
sir with great respect i already tried this excersice but the problen is when i submit without inserting data its created bcz i mentioned in action process form bcz i want to insert the data in same time but its posted without checking validation whys its like that..bcz action is actually its inserting query,…..waiting for ur response
Your feedback is appreciated…..
Thank you so much….
keep reading our blogs… 🙂
variable declared nahi kar pa raha html form pe
Hello Vivek,
Variables can’t be declared in html , for that you need to use javascript.
this post is just quite helpful.thanks alot
Hello Benson,
That sounds really great ! Keep reading our other blog posts for getting more coding tricks.
Catch up new posts from here
Regards,
FormGet Team
it is very helpful,nice tutorial
thanks
Guys really cool turtorial!!! But i have just one question?How will it show a message for successful registration or not?
what is the variable $data
I would ask you to give me the answer to what it refers to the last class in the css folder-.formget
Thanks a lot.
All praise to you.
good
nice sharing …
ooops, validation.php code looks great but unfortunetely not working when i submit the form. Not validating required fields, the webpage shows emptily.. I cant get what was the mistake with that code… html and css files works very finely but not php file.. Admin will you please help me? i have set everything right. using windows 8-64bit, iis 8, php has installed.
hi!,I like your writing so a lot! percentage we communicate extra approximately your article on AOL?
I need an expert on this space to solve my problem.
May be that’s you! Taking a look forward to see you.
Hello Solar Shower,
Thanks for the wonderful appreciation!
Let me know how can I help you.
Regards,
FormGet Team
hi thanks for the tutorial..but can u tell me how to send this form data to next page for further processing like database connectivity…
Nice post it,s really help me out easy and best technique to validate the form
ThnQ for posting…………….
Really it’s a well done course about php form validation.
I need more courses about php/ maysql, mainly using OOP and PDO. I want to create dynamic website by myself.
Thank you so much
Chikhaoui Mongi
I need more lessons about php
Hi everyone, it’s my first pay a quick visit at this
web page, and post is in fact fruitful in support of me, keep
up posting these types of articles.
Bro when i save and run the html file the php code is not working for me properly. 🙁 when i click submit button the page switches into a php coding page 🙁 what to do need your help pls
Hi,
For your information, .html page doesn’t support PHP coding.
So, instead of .html, save your file as .php(for example, save “file.html” as “file.php”).
your information is very useful…thank you
Post is so helpful, thanks alot for sharing.
Hi…….!
I couldn’t insert data in sql tables while using the actions = htmlspecialchars(); and viceversa while using action=”example.php”. do you help me sir?
check your connection Query it works or not. there can be many mistakes like your field names,database field names such like check line by line(debug) then u will get where actually u r wrong
thanks for contribution
Try it
function myFunction() {
alert(“Hello! I am an alert box!”);
}
tnx a lot, but I didn’t not see any code for page redirection after the is completed…….
nice post it very helpful
trim($data);
stripslashes($data);
htmlspecialchars($data);