How to Validate Forms in both sides using PHP and jQuery
Hi guys and welcome to a new tutorial of yensdesign.com! Some of you ask us about the possibility of create a tutorial about how to validate forms in server side (using PHP). So i wrote a tutorial about it, adding some interesting features with jQuery:
We are going to learn how to validate your forms using PHP and jQuery in both sides: client side (using javascript with jQuery) and server side (using PHP). It will be interesting to see how to use regular expressions to validate different kind of e-mails, passwords and more.
As always, here you have a preview of what we are going to do:
You can try the living example before continue reading the tutorial. Remember that if you want to try the server side, you need to disable javascript in your web browser!
Tested in: Firefox, Internet Explorer 6 & 7, Opera, Safari & Chrome.
Let’s learn guys!
Introduction
As you know, we are asking you wich tutorials do you want to see in yensdesign and as i told you, you can send us more suggestions and feedback in our forums.
On of these suggestions is about how to validate forms in server side using PHP, so in this tutorial we will make use of PHP and jQuery to validate all fields in both sides:
- Client side: Using javascript with jQuery.
- Server side: Using PHP.
We will make use of regular expressions and if you don’t know about them, you will notice very soon their power. By the way, you can check out this source to learn more about regular expressions in different languages.
At the end of the tutorial, we will get a final real working example that will validate our fields with / without javascript enabled, but always making use of the server side validaton.
Let’s dive into the tutorial!
Step 1: First approach to the xHTML Layout
In this case we will create a simple HTML layout showing our form. In a first approach the HTML will look like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>yensdesign.com - Validate Forms using PHP and jQuery</title> <link rel="stylesheet" href="css/general.css" type="text/css" media="screen" /> </head> <body> <a id="logo" title="Go to yensdesign.com!" href="http://www.yensdesign.com"><img src="css/images/logo.jpg" alt="yensdesign.com" /></a> <div id="container"> <h1>Registration process</h1> <div id="error"> <ul> <li><strong>Invalid Name:</strong> We want names with more than 3 letters!</li> <li><strong>Invalid E-mail:</strong> Stop cowboy! Type a valid e-mail please :P</li> <li><strong>Passwords are invalid:</strong> Passwords doesn't match or are invalid!</li> <li><strong>Ivalid message:</strong> Type a message with at least with 10 letters</li> </ul> </div> <div id="error" class="valid"> <ul> <li><strong>Congratulations!</strong> All fields are OK ;)</li> </ul> </div> <form method="post" id="customForm" action=""> <div> <label for="name">Name</label> <input id="name" name="name" type="text" /> <span id="nameInfo">What's your name?</span> </div> <div> <label for="email">E-mail</label> <input id="email" name="email" type="text" /> <span id="emailInfo">Valid E-mail please, you will need it to log in!</span> </div> <div> <label for="pass1">Password</label> <input id="pass1" name="pass1" type="password" /> <span id="pass1Info">At least 5 characters: letters, numbers and '_'</span> </div> <div> <label for="pass2">Confirm Password</label> <input id="pass2" name="pass2" type="password" /> <span id="pass2Info">Confirm password</span> </div> <div> <label for="message">Message</label> <textarea id="message" name="message" cols="" rows=""></textarea> </div> <div> <input id="send" name="send" type="submit" value="Send" /> </div> </form> </div> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="validation.js"></script> </body> </html>
As you can see we have created all divisions that will appear (or not) in our tutorial. Some of these divisions won’t be visible as default, but we will add some conditionals in PHP and CSS to get this. So these are the divisions:
- #container: contains all divisions
- #error: contains a list of possible errors after submitting the form
- #error.valid: contains the “congratulations phrase” if all it’s OK
- #customForm: contains our form
So now we have our xHTML layout ready let’s add some style with CSS.
Step 2: Adding style with CSS
It will be fast guys, just take a look at the general.css code:
@CHARSET "UTF-8";
/******* GENERAL RESET *******/
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em,
font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody,
tfoot, thead, tr, th, td {
border:0pt none;
font-family:inherit;
font-size: 100%;
font-style:inherit;
font-weight:inherit;
margin:0pt;
padding:0pt;
vertical-align:baseline;
}
body{
background: #fff;
line-height:14px;
font-size: 12px;
font-family: Arial, Verdana, Helvetica, sans-serif;
margin:0pt;
cursor:default;
overflow: hidden;
}
html,body{
height:100%;
text-align: center;
}
.clear{
clear: both;
height: 0;
visibility: hidden;
display: block;
}
a{
text-decoration: none;
}
strong{
font-weight: 700;
}
/******* GENERAL RESET *******/
h1{
font-weight: 700;
font-size: 18px;
line-height: 1.2em;
border-bottom: 1px dotted #6b9ef1;
color: #5f95ef;
margin-bottom: 1em;
}
/******* LOGO *******/
#logo{
margin-top: 1em;
display: block;
}
/******* /LOGO *******/
/******* CONTAINER *******/
#container{
width: 600px;
margin: 40px auto;
text-align: left;
}
/******* /CONTAINER *******/
/******* FORM *******/
#customForm{
padding: 0 10px 10px;
}
#customForm label{
display: block;
color: #797979;
font-weight: 700;
line-height: 1.4em;
}
#customForm input{
width: 220px;
padding: 6px;
color: #949494;
font-family: Arial, Verdana, Helvetica, sans-serif;
font-size: 11px;
border: 1px solid #cecece;
}
#customForm input.error{
background: #f8dbdb;
border-color: #e77776;
}
#customForm textarea{
width: 550px;
height: 80px;
padding: 6px;
color: #adaeae;
font-family: Arial, Verdana, Helvetica, sans-serif;
font-style: italic;
font-size: 12px;
border: 1px solid #cecece;
}
#customForm textarea.error{
background: #f8dbdb;
border-color: #e77776;
}
#customForm div{
margin-bottom: 15px;
}
#customForm div span{
margin-left: 10px;
color: #b1b1b1;
font-size: 11px;
font-style: italic;
}
#customForm div span.error{
color: #e46c6e;
}
#customForm #send{
background: #6f9ff1;
color: #fff;
font-weight: 700;
font-style: normal;
border: 0;
cursor: pointer;
}
#customForm #send:hover{
background: #79a7f1;
}
#error{
margin-bottom: 20px;
border: 1px solid #efefef;
}
#error ul{
list-style: square;
padding: 5px;
font-size: 11px;
}
#error ul li{
list-style-position: inside;
line-height: 1.6em;
}
#error ul li strong{
color: #e46c6d;
}
#error.valid ul li strong{
color: #93d72e;
}
/******* /FORM *******/
As always we make use of our cool CSS reset snippet and add some interesting parts to the specific tutorial.
Just notice that we have defined some .error classes that we will use in the jQuery part to make our tutorial a little more cool and friendly user
![]()
Next part, the javascript validation!
Step 3: Validation in the client side with jQuery
Yeah guys, because it could not be otherwise we will use jQuery to make the validation part in the client side. We will add / remove some .error classes to make our form a little more intuitive for the final user.
So first of all, remember that all the following code will be in the $(document).ready() of jQuery and all will be a part of the javascript file named validation.js (original, uh?).
So let’s save references to some DOM elements that we will often:
//global vars
var form = $("#customForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");
As you may notice, all references are form related.
Now let’s define our validation functions that will help us in the validation process:
- validateEmail(): we only allow valid emails!
- validateName(): we only allow names with more than 3 letters
- validatePass1(): we only allow passwords with at least 5 characters
- validatePass2(): we only allow it if passwords are equal
- validateMessage(): we only messages with more than 10 letters
function validateName(){
//if it's NOT valid
if(name.val().length < 4){
name.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
return true;
}
}
function validatePass1(){
var a = $("#password1");
var b = $("#password2");
//it's NOT valid
if(pass1.val().length <5){
pass1.addClass("error");
pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
pass1Info.addClass("error");
return false;
}
//it's valid
else{
pass1.removeClass("error");
pass1Info.text("At least 5 characters: letters, numbers and '_'");
pass1Info.removeClass("error");
validatePass2();
return true;
}
}
function validatePass2(){
var a = $("#password1");
var b = $("#password2");
//are NOT valid
if( pass1.val() != pass2.val() ){
pass2.addClass("error");
pass2Info.text("Passwords doesn't match!");
pass2Info.addClass("error");
return false;
}
//are valid
else{
pass2.removeClass("error");
pass2Info.text("Confirm password");
pass2Info.removeClass("error");
return true;
}
}
function validateMessage(){
//it's NOT valid
if(message.val().length < 10){
message.addClass("error");
return false;
}
//it's valid
else{
message.removeClass("error");
return true;
}
}
As you can see, we are adding and removing .error classes and changing text values if needed to show the user what fields are wrong.
Now we have defined all validation functions, we only need to manage events. Here you have what we are going to do:
- Validate the name field in: blur and keyup events.
- Validate the email field in: blur event.
- Validate the password fields in: blur and keyup events.
- Validate the message field in: blur, and keyup event.
- Validate all fields in: submit form event.
Therefore the code would be:
//On blur
name.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
name.keyup(validateName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function(){
if(validateName() & validateEmail() & validatePass1() & validatePass2() & validateMessage())
return true
else
return false;
});
As you can see, it’s very easy to control whatever we want by using jQuery and some functions. So now that we have done the cliend site, let’s move to the server side!
Step 4: Validation in the server side with PHP
Now that we have the client side done, let’s use the power of PHP to complete our tutorial.
Some of you may think that we don’t need the server side validation but it’s a big error thinking about it. Remember that we can’t trust in the client side. In example: users can disable javascript in their browsers and send us undesired values.
So first of all we must create a new .php file named validation.php that will contains our validation functions written in PHP:
<?php
function validateName($name){
//if it's NOT valid
if(strlen($name) < 4)
return false;
//if it's valid
else
return true;
}
function validateEmail($email){
return ereg("^[a-zA-Z0-9]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$", $email);
}
function validatePasswords($pass1, $pass2) {
//if DOESN'T MATCH
if(strpos($pass1, ' ') !== false)
return false;
//if are valid
return $pass1 == $pass2 && strlen($pass1) > 5;
}
function validateMessage($message){
//if it's NOT valid
if(strlen($message) < 10)
return false;
//if it's valid
else
return true;
}
?>
As you can see we have defined 4 functions:
- validateName(): checks if name has at least 4 letters
- validateEmail(): checks if email is valid
- validatePasswords(): checks if passwords are equal and have at least 5 letters
- validateMessage(): checks if message has at least 10 letters
It’s almost done guys, we only need to add some conditionals to our index.php. If you remember, we said that we are going to add some conditionals in the PHP, so it’s time to do that:
- We will display #error division only if there are at least one error.
- We will display #error.valid division only if all fields are OK.
So here you have the final index.php layout:
<?php
require_once("validation.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>yensdesign.com - Validate Forms using PHP and jQuery</title>
<link rel="stylesheet" href="css/general.css" type="text/css" media="screen" />
</head>
<body>
<a id="logo" title="Go to yensdesign.com!" href="http://www.yensdesign.com"><img src="css/images/logo.jpg" alt="yensdesign.com" /></a>
<div id="container">
<h1>Registration process</h1>
<?if( isset($_POST['send']) &amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp; (!validateName($_POST['name']) || !validateEmail($_POST['email']) || !validatePasswords($_POST['pass1'], $_POST['pass2']) || !validateMessage($_POST['message']) ) ):?>
<div id="error">
<ul>
<?if(!validateName($_POST['name'])):?>
<li><strong>Invalid Name:</strong> We want names with more than 3 letters!</li>
<?endif?>
<?if(!validateEmail($_POST['email'])):?>
<li><strong>Invalid E-mail:</strong> Stop cowboy! Type a valid e-mail please :P</li>
<?endif?>
<?if(!validatePasswords($_POST['pass1'], $_POST['pass2'])):?>
<li><strong>Passwords are invalid:</strong> Passwords doesn't match or are invalid!</li>
<?endif?>
<?if(!validateMessage($_POST['message'])):?>
<li><strong>Ivalid message:</strong> Type a message with at least with 10 letters</li>
<?endif?>
</ul>
</div>
<?elseif(isset($_POST['send'])):?>
<div id="error" class="valid">
<ul>
<li><strong>Congratulations!</strong> All fields are OK ;)</li>
</ul>
</div>
<?endif?>
<form method="post" id="customForm" action="">
<div>
<label for="name">Name</label>
<input id="name" name="name" type="text" />
<span id="nameInfo">What's your name?</span>
</div>
<div>
<label for="email">E-mail</label>
<input id="email" name="email" type="text" />
<span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
</div>
<div>
<label for="pass1">Password</label>
<input id="pass1" name="pass1" type="password" />
<span id="pass1Info">At least 5 characters: letters, numbers and '_'</span>
</div>
<div>
<label for="pass2">Confirm Password</label>
<input id="pass2" name="pass2" type="password" />
<span id="pass2Info">Confirm password</span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" cols="" rows=""></textarea>
</div>
<div>
<input id="send" name="send" type="submit" value="Send" />
</div>
</form>
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="validation.js"></script>
</body>
</html>
As you can see we have included the validation.php file before call our validation functions and added some calls to our validation functions to check fields when form is submited.
We have used short notation PHP in conditionals to keep the HTML cleaner and easier to read.
We are showing errors / “congratulations phrase” as needed and now you only need to know what are you doing to do with this validated values
Step 5: Testing our Validated Form!
That’s all guys, I hope you find it useful and use this tutorial to improve a little more your websites.
Remember that if you want to try the server side, you need to disable the javascript in your web browser. In Firefox it’s in Tools > Options > Content uncheck the “Enable Javascript” checkbox.
You can try the tutorial online here to see how It is working and download here all sources.
Remember that you can solve your doubts in our forums and follow os on Twitter to know more about what are we doing in any moment!
See you on next tutorial and remember that we want you suggest tutorials to write!
Enjoy this post?
Your vote will help us to grow this website and write more entries like this one :)





honestly: fucking horrible.
shitty (x)html, shitty css, shitty javascript and shitty php.
stop writing articles, please.
@thr Thanks for posting and for the feedback!
The living demo has passed the XHTML 1.0 Transitional and the CSS code has passed the 2.1 validation! So shit goes to the javascript and the php code only hehe.
Sorry but I will continue posting tutorials ^_^
Where are the Javascript validation functions? The php ones are posted twice.
@me Thanks for posting! Fixed!
@adrian Mato Gondelle: Even though I wasn’t too interested in this tutorial (as my framework -code igniter- handles pretty neat php responses, I just wanted to thank you for all your tuts (in contrast to the first commenter). This blog is one of the few each year which made it to my homepage and I am planning on integrating another tut in my open source project blogora.
Thanks a lot
@David Thank you so much for your comment! I understand that somebody doesn’t like my tuts, but the goal of theme are share my little knowledge about webdesign and coding and I love to see people using them for their personal projects
Wait, you’re dutch and from hilversum…!?!?! (based on the text on your dark elegance theme thing… I hope I am right because your facebook is spanish and you aren’t listed in “de telefoongids”)…
Nja, heel veel success en I hope I am not messing up some facts currently.
Echt een prachtige site en echt heel veel succes met al je projecten en overtuig je baas dat er wat moet veranderen aan de website van mediamonks. Ik loop dagelijks van en naar station hilversum en daar ergens is mediamonks ook gevestigd volgens mij
Toch wel leuk om nog zo nu en dan een nederlander tegen te komen op het internet :P:P
@David Mulder hahaha noooo! It’s a copy paste from other site to fill the divisions! ^_^”
[...] How to Validate Forms in both sides using PHP and jQuery | yensdesign - Tutorials, Web Design and Co… Validate forms with jQuery AND PHP (tags: webdesign tutorial CSS usability jQuery html coding php) [...]
its nice but u should make as Ajax thing, i mean the response, u have added only validation, hope next article will be Ajax response.
by they way, better not to make unwanted comments
@Yoosuf Thanks for posting!
It is NOT AJAX! We are only using javascript to validate the form!
Hola Adrián:
Tu blog está genial, no hagas caso de comentarios de gente que no entiende.
Sólo decirte que el código javascript de validación no aparece. Aparece 2 veces el código php.
En otro mensaje anterior dices que lo has corregido, pero sigue saliendo
1 saludo!
@Rekeb Thanks for posting!
Arg! I was sure I have fixed the problem with javascript code! Now it’s fixed
@Adrián Mato Gondelle: Saying that the code is ‘ok’ b/c it passes validation just shows how little you know about this stuff, allow me to elaborate on WHY the four parts are shitty:
(x)html: It contains markup which isn’t used on every request, for example the error/ok-validation-feedback-blocks should be rendered using pure javascript, what happens when someone without js/css-availability (for example: people with disorders or google-bot) goes into this site? They will see the error messages at the top first and think they did something wrong.
css: Admittedly this is the ‘least bad’ of the four code segments, but over-abuse of IDs and using of IDs where it doesn’t make sense (for example the #error id should probably be a class)
javascript: using global variables, and it even seems as if you forgot to add parts of the javascript code? since the php-validation-code is on both the “client” and “server” parts of validation, also the javascript is horribly static requiring editing of the validation code for every new element you add, sigh.
php: intermixed with the (x)html putting validation logic in the template, using the now deprecated ereg-functions, the regex for the email is just HORRIBLE and doesn’t even account for close to all possible emails.
php+javascript: You seem to be duplicating the validation logic on both the client and server, redundant work.
All in all: HORRIBLE CODE.
@thr Thanks for posting one more time, but it seems you haven’t read the tutorial or don’t understand what is going on.
You said: “just shows how little you know about this stuff”, “php+javascript: You seem to be duplicating the validation logic on both the client and server, redundant work.”
- You are completily wrong! It’s VERY IMPORTANT do that “redundant” work, because if you don’t know, clients (as we said in the tutorial) can disable the javascript code in webpages and make whatever they want in your database without validation
- In the other hand, you are completily wrong at your interpretation about google bot. If you check the code, we test via PHP if someone submitted the post, so you are wrong.. one more time
- About the javascript… we don’t pretend to create a plugin or something like that, just show how to validate a form hehe
- The PHP is interlined with the xHTML to make the tutorial easier to write and explain, because we are not learning about how to applicate a MVC in each tutorial, that’s all.
By the way, I am not saying that it has the best practices in web development, it’s a tutorial to “show the way” to understand some concepts.
Thanks for the feedback anyway, it’s important to know all opinions of readers
El tutorial me ha venido genial para validar unos formularios con jQuery. Yo en lugar de usar PHP uso JSP, pero asi mismo, es un trabajo impecable. Muchas gracias!!
1 saludo!!
@Rekeb Thanks one more time!
Remember you can download directly all ours tutorials at the end of the posts to check all the files working
Hey adrian awesome site, im having trouble, im trying to add a field for phone numbers but having trouble with the regex.
@Jaswinder Thank you so much!
Here you have this snippet, hope it helps you http://snippets.dzone.com/posts/show/597
[...] How to Validate Forms in both sides using PHP and jQuery … [...]
@thr - you’re certainly incorrect in saying that the duplicated validation is redundant - a point I’m suprised at considering you comments concerning accessibility earlier.
Whilst the Javascript and PHP here might not be coded as you like, the principle is correct - client side validation to provide an instant feedback mechanism. Server side validation to do the real, essential work.
If you think for one minute that client side validation is sufficient then your PHP code has far more fundamental problems than simply being mixed with (X)HTML.
[...] How to Validate Forms in both sides using PHP and jQuery [...]
I was kind of hoping to see unified validation.
The problem with your approach is that if you update the validation on, lets say name length, you must change the client-side and server-side code, which inevitably will lead to bugs on one side or the other, or just plain inconsistencies.
I like to follow DRY principles where possible.
I’m not sure how -best- to solve that problem.
@Luke Interesting thought, but I don’t find any solution to this problem… It seems inevitable.. or not, anyone knows? :S
Its good that someone has gone into this subject. I am all for giving immediate feed back on the validity of a form.
However, the method described above is but one of oh 1374 ways that it could be done.
I personally would use arrays and jQuery ajax. The problem with the above is that certain code algorithms are being repeated over and over again. Think about it…
have an array:
$regexs['first_name'] = “^….*$”;
$regexs['name'] = “^….*$”;
$regexs['email'] = “^[super fun regular expression for email checking]*$”;
… etc …
$errors['first_name'] =”First names must be atleast 3 chars… sorry Asian people”;
$errors['name'] =”First names must be atleast 3 chars… sorry Asian people”;
$errors['email'] =”Please give a real email address”;
… etc …
Then using foreach loops you can wrap the validation and present errors into one function. You can also ajax the inputs so that all validation is done in PHP which has superior regular expression tools than Javascript. The method above uses ALOT of repetitive writing and coding.
Tomato, Tomato the end result should be live real time input validation to help the user fill in the forms nicely.
Kudos for the post.
@Rob Yeah, I am totally agree with you, but as in other tutorials I try to keep it simple to let all kind of people understand the tutorial. Begginers will understand it fast and more experienced users can think about how to optimize the “concept” just that.
Thanks for posting!
[...] YensDesign blog has a recent post that steps you through the entire process (down to every detail in the code) of making a form [...]
How can I connect a mysql database to this form?
@snarf Hi thanks for posting! You must use the mysql provided in the tutorial, to create the table. Then you must change first lines of the php file to connect to your database.
Good luck!
Hi Adrian,
Thanks for getting back so quick.
Had another scan of all the code, and there is no mention of a connection to mysql!!!!
I am sorry snarf! I was thinking about other tutorial! In this tutorial there is only the validation in 2 sides but nothing about databases, right?
You can check this tutorial about creating a shoutbox tutorial with php and mysql and see how do a connection to a mysql database, and more: http://yensdesign.com/2009/01/create-a-shoutbox-using-php-and-ajax-jquery/
Thanks Adrian
Hi, about the quality of the code, for demonstration purposes it fits perfectly.
There’s plenty of tutorials about good semantic xhtml and about compact clever css.
There’s other places to learn javascript, jQuery or PHP.
The concept being explained, is indeed explained clearly.
The question about double validation… well there are at least 2 waysto solve the problem:
1 - Write php code (one time) that generetes the validation on the client side and the validation on the server side, this way maintenace must always be on one place, the generator!
2 - Try Jaxter, the javascript server, this way you can reuse javascript validation code on both sides, maintenace is done only in one place also. (I haven’t tried Jaxter, but that’s exacly one the key benefits of having a javascript server.
Keep up the tutorials!
@luis good point! Thank you so much for share that with us!
[...] How to Validate Forms in both sides using PHP and jQuery … [...]
[...] See the rest here: How to Validate Forms in both sides using PHP and jQuery … [...]
[...] 4 - How to Validate Forms in both sides using PHP and jQuery [...]
[...] How to validate forms using jQuery & PHP [...]
Thanks for the tutorial. Really Nice work. Do you have anything that covers interacting with a database via AJAX/PHP without refreshing page content?
It’s good to know that some people still find time to work on tutorials like these.
Thanks again.
Good tutorial but very rough around the edges. The email validation method for the java side is not even shown, I had to go to the full source to find it. Also, the presented code doesn’t always cooperate with IE, and for that reason, I removed the shortcut variables you used to make things run smoothly. Additionally, there is a typo in the php code presented, in the password validation method, it should be >= 5, not > 5 Other than that, a very good tutorial.
Thank you for posting this.
Its help me a lot
Fine info… I’ll use it… thanks
helped me perfectly with what I needed. Clear and very easy to follow. Cheers!
Question about writing the request I wrote the $.ajax() code but am not sure where to put it. Right now if have it in if(validateEmail()){$.ajax()…..} but not working. Is this request wrong or is it in the wrong place? Thanks
$.ajax({
type: “POST”,
url: “bin/process.php”,
data: dataString,
success: function() {
$(’#contact_form’).html(”");
$(’#message’).html(”Contact Form Submitted!”)
.append(”We will be in touch soon.”)
.hide()
.fadeIn(1500, function() {
$(’#message’).append(”");
});
}
});
http://docs.jquery.com/Ajax/jQuery.ajax
[...] How to Validate Forms in both sides using PHP and jQuery [...]
Hi,
Thanks for tut. This is exaclty what I was looking for! both sides….
good job…
PS. If someone done like it …. well not everyone have to use it espacially when they dont like it
And CSS or JS and php code can be presonalized… its just an idea and not copy / paste …
I guess thats the whole point of tutorials
Good job
[...] 16. How to Validate Forms in both sides using PHP and jQuery [...]
It would be good when writing a tutorial to use best practices.
I agree with other posters here, the duplication of the validation is a bit annoying, it would be better to come up with a DRY way of doing this, and that’s what I was expecting when I clicked this link.
Also, all those global variables in javascript are terrible. There is no reason for that all. A global variable called “name”?? You’re looking for trouble here. The least you could do is wrap those all in an object.
Keep in mind that you might post a tutorial for people to get the “basic idea” but there will be plenty of people that copy the code exactly as it’s written, so it would be best to have the proper standards applied.
Oh, by the way no reason to use a Transition doctype, doctype should be Strict.
Transitional was only good for one thing, exactly what it says…when a site was in transition from one doctype to another. Anything brand new should always be strict.
thanks so much
[...] How to Validate Forms in both sides using PHP and jQuery (tags: jquery php validation forms tutorial) [...]
[...] How to Validate Forms in both sides using PHP and jQuery | yensdesign - Tutorials, Web Design and Co… (tags: coding howto php development javascript tutorials programming jquery validation) [...]
[...] How to Validate Forms in both sides using PHP and jQuery [...]
I love the tutorial im try to figure out how to validate different forms on the same page thanks
[...] 16. How to Validate Forms in both sides using PHP and jQuery [...]
Hi! Thanks for a great tutorial. Is it possible to use mail()? Can you please show me an example where to put the mail() code?
Best regards Randy
mate, thanks a lot for this tute. I see that most replies to you are positive, which is great. Those that are negative should keep their options to themselves- if they feel they can do better then they should go and do that. Your effort is much appreciated.
Thanks again!
Regards, Adam
I don’t give a s**t what others say,
when people like your-self go out there way to help others by providing useful information like this its always worth a thanks.
keep up the good work m8.
Thumbs up
The email validation part can generate false negative checks.
For example, the website http://www.nn.hr is absolutely valid (Croatian goverment publications) , and email “[REMOVE_SPAM_]ads@nn.hr[REMOVE]” (remove stuff inside brackets) is valid also, but doesn’t pass though your validation form :/
Nice tutorial. For those who are in to regular expressions, then rewriting the basics shouldn’t be a problem.
One small problem - the form as displayed in FF3.1b3 with web developer and tab toolbars creates page overflow if multiple error messages are displayed, so you need -
html, body {
overflow:auto
}
in the css.
@thr & JeffL - The purpose of a tutorial is not to spoon feed people, but to arm them with information that can make them think of solutions for their own circumstances. In this case, the php might not be the way I would do it, the css is definitely not the way I would do it and the java is probably not exactly the way I would do it either… but all three parts combined have given me an insight into how to solve a problem that I have been having. If someone is lazy enough to cut and paste and use that professionally, then they shouldn’t be in the game in the first place.
@Adrian - Thanks for the tips. You have made my life today far easier than it was going to be.
I agree with the first poster. Repetition, too much hard coding, limited to “simple” forms, etc. etc. And there is more to XHTML and CSS then passing a validation test, semantics in particular.
correct the code php there is one small error
function validatePasswords($pass1,$pass2) {
//if DOESN’T MATCH
if(strpos($pass1,’ ‘) !== false)
return false;
//if are valid
return $pass1 == $pass2 && strlen($pass1) >= 5;
}
[...] 16. How to Validate Forms in both sides using PHP and jQuery [...]
[...] 16. How to Validate Forms in both sides using PHP and jQuery [...]
Tio, el ingles de uno de nosotros dos esta muy mal “paswords doESn’t match”. Espero que sea el tuyo
Me ha ayudao mucho esto y lo del webos (aunque mola mas el mio) y me ha servido para la clase de informatica (tengo a un garrulo que dice usar la tablas pa organiozar las cosas en el front page).
Desgraciadamente esperaba algo de ajax.
Igualmente muy buen trabajo y gracias.
Ahora solo queda que no seas español pero me da pereza a estas horas
[...] How to Validate Forms in both sides using PHP and jQuery [...]
[...] 8. How to Validate Forms in both sides using PHP and jQuery [...]
very intersting
nice job
“….but I don’t find any solution to this problem… It seems inevitable.. or not, anyone knows?….”
a php function that serves both client (via ajax) and server side requests…here is just a few snippets of how I accomplished this…
$(document).ready(function(){
$(”.validate”).blur(function(){
var el = $(this);
$.ajax({
type: ‘POST’,
url: ”,
data: { action: ‘validate’, rule: el.attr(’id’), value: el.attr(’value’) },
async: false,
success: function(valid) {
el.next(’span’).remove();
if(valid) {
el.after(”) ;
el.css( ‘background-color’, ‘#FFFFFF’ );
} else {
el.after(”);
el.css( ‘background-color’, ‘#FFFF99′ );
}
},
});
});
});
function validate($rule,$value) {
global $web_path;
$valid = TRUE;
$invalid = FALSE;
switch($rule) {
case “url”:
$output=(filter_var($value, FILTER_VALIDATE_URL)) ? $valid: $invalid;
break;
}
return $output;
}
[...] 8. PHP + jQuery表单验证 [...]
[...] Aqui el enlace. [...]
if you want a simple validate just try to read this code :
/* return a string where left & right spaces are removed */
function trim(s){ return s.replace(/^\s*|\s*$/g,”"); }
/* true if ’s’ is a 4 digit year, false if not */
function isYear(s){ return (s.search(/^\d{4}$/) == -1) ? false:true; }
/* true if ’s’ is empty, false if not */
function isEmpty(s){ return (trim(s).length > 0) ? false:true; }
/* true if ’s’ is a valid email address, false if not */
function isEmail(s){ return (trim(s).search(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/) == -1) ? false:true; }
/* true if ’s’ is in date format, false if not! ex: 01-01-2004, 1-1-2004, 01-1-2004 - all valid format */
function isDateFormat(s){ return (trim(s).search(/^(\d{1,2})(-)(\d{1,2})(-)(\d{4}$)/) == -1) ? false:true; }
/* true if ’s’ is a valid date value, false if not */
function isDateValid (s){
var ar = s.split(”-”);
var m = parseInt(ar[0],10) - 1, d = parseInt(ar[1],10), y = parseInt(ar[2],10);
var dD = new Date(y,m,d);
return ((d==dD.getDate()) && (m==dD.getMonth()) && (y==dD.getFullYear()));
}
/* true if ’s’ is a number (w/ or w/out unary +/-, w/ or w/out a dot), false if not! ex: 100, 10., 100.99 */
function isNumber(s){ return (trim(s).search(/^([+-]{0,1}\d{1,}([.]{0,1}\d*)*)$/) == -1) ? false:true; }
/* true if ’s’ is a whole number (w/ or w/out unary +/- symbol), false if not */
function isWholeNumber(s){ return (trim(s).search(/^([+-](\d+)|(\d+))$/) == -1) ? false:true; }
/* true if ’s’ is valid password (only all of these [0-9,a-z,A-Z,_-]), false if not. */
function isPasswordCombinationValid(s){
if(s.search(/^([-_a-z\d]+)$/i) == -1) return false; /* only these [0-9,a-z,A-Z,_-] */
if(s.search(/[a-z]/i) == -1) return false; /* letters */
if(s.search(/\d/) == -1) return false; /* digits */
if(s.search(/[-_]/) == -1) return false; /* _ & - */
return true;
}
/* true if ’s’ is a valid user id (only any combination of these [0-9,a-z,A-Z,_]), false if not */
function isUserIdCombinationValid(s){ return (s.search(/^([_a-z\d]+)$/i) == -1) ? false:true; }
/* true if ’s’ is in the format (99)999-999 */
function isTel_Fax(s){ return (s.search(/^([(])(\d{1,2})([)])(\d{3,3})(-)(\d{4,4})/) == -1) ? false:true; }
/* true if ’s’ is a valid program code (only any combination of these [0-9,a-z,A-Z,_]), false if not */
function isProgCodeCombinationValid(s){ return (s.search(/^([_a-z\d]+)$/i) == -1) ? false:true; }
[...] 16. Как проверить форму с двух сторон (пользовательской и
[...] How to Validate Forms in both sides using PHP and jQuery | yensdesign - Tutorials, Web Design and Co… [...]
Very good brother! Fantastic script AJAX. And… thr, you are ridiculous, the script is perfect … redundant is your face, noob! =P
By XandynN
This is great but can you expand for us beginners how to send it to we just add it to the action “”?
Or do we have to add it after the validation.php :S
Nice one. One thing though.. The live example doesn’t allow some valid email adresses, specifically ones containing a plus sign.
@adrian (and Steve)
I won’t say your article is shit*y, but it sure is superficial. Only true beginners will learn something, and I’m afraid they’ll have to get rid of it later.
You thought that thr was wrong when he sayed that writing validating code both in Js and PHP was wrong. But he didn’t say that you needn’t validate with both, just avoid _writing_ both. Haven’t you ever heard of PEAR::HTML_QuickForm in the past 10 years or so? Or ever used any JS-HTML helpers in a recent PHP framework?
A tutorial has to simplify things, but it also has to point toward good pratices and further references. You seem to lack the culture that would allow you to write interesting articles. Sadly, most bloggers write about subjects they don’t master at all.
Please, try to run a simple spell check before posting a document like this. Poor grammar and spelling errors make this tutorial hard to follow. I am not condemning your knowledge in the subject area, but your lesson is difficult to grasp when your message lacks care. A simple program like MS Word usually does the job. Thanks.
Hey, first thanks for this article. There are probably some stuffs that could be optimized, but i sincerely think this helps (at least for beginners like me)! So thr or Rogo you should maybe tell us about what YOU wrote before criticizing.
I have a question about this, could you help about this :
I have a group of radio button for Gender select (are you a man or a woman).
I want to check if one of those 2 radio buttons is checked but i can’t succeed, i really need help.
Which is the syntax ?
Do the both radio button must have same or different ID ?
Help would be really appreciated…
Hi,
It all worked for me.
I just have one question, is it possible to add a code tot validation.php so that you recieve the form as an email?
If so, what is that code?
(I do not know much about php so don’t be harsh…)
Thanks
Is this post closed?
If not, I would like an anwer to my question:
“I just have one question, is it possible to add a code to validation.php so that you recieve the form as an email?
If so, what is that code?”
(I do not know much about php so don’t be harsh…)
Thanks
Muito bom !!!vou testar agora !!!
[...] referred from these links…. http://yensdesign.com/2009/01/improving-search-boxes-with-jquery/ http://yensdesign.com/2009/01/how-validate-forms-both-sides-using-php-jquery/ the complete code looks like this… [...]
[...] create a username and email check. That was a great moment…(wipes away a tear). Thanks to yensdesign.com, Roshan’s Blog and the [...]
Hey Brother… i just want to say thanks for the tutorial it was great. but i just want to suggest one thing, that is Please make this tutorial a video. it’s nicer if it’s in a video format. Keep up your good work…
Can i use your work… For non commercial uses of course
thanxxx i like it
Hi,
The tutorial was really a cool. The basics are very clearly penned out. Thanks a ton for such a wonderful tutorial.
GREAT PIECE OF WORK…..HOWEVER SEEMS TO HAVE NO BETTER SERVERSIDE VALIDATION WITH JAVASCRIPT ENABLED..
HOPE U GUYS WILL COME UP WITH IT……
Hello,
Thanks a lot for this. It really is a good starting point for me.
All I need now is a mail function. Is there any way you, or someone, could show how to send this to email with php?
Thanks once again.