Form validation with PHP & JavaScript

pradeep's Avatar author of Form validation with PHP & JavaScript
This is an article on Form validation with PHP & JavaScript in PHP.
Rated 5.00 By 1 users
If you want to validate a form without submitting it, you can use two methods, one is pure client side JavaScript and the other being a mix of JavaScript and server-side scripting which can be PHP,ASP.JSP,Perl or anything for that matter.
First I will give an example of pure JavaScript validation
The HTML:
HTML Code:
<html>
 JavaSrcipt Form Validation<head>
 <script language="JavaScript" type="text/javascript">
 function validateForm(oForm)
 {
 	//oForm refers to the form which you want to validate
 	oForm.onsubmit = function() // attach the function to onsubmit event
 	{
 		var regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
 		if(oForm.elements['email'].value.length<1)
 		{
 			alert("You cannot leave the email field empty");
 			return false;
 		}
 		else if(!regex.test(oForm.elements['email'].value))
 		{
 			alert("Invalid email address format");
 			return false;
 		}
 		return true;
 	}
 }
 </script>
 </head>
 <body>
 <form name="email_check" method="post">
 Enter email : <input type="text" name="email" />
 
 <input type="submit" value="Check & Submit" />
 </form>
 <script language="JavaScript">
 new validateForm(document.forms['email_check']);
 </script>
 </body>
 </html>
In the second case, we'll use XMLHTTP to validate the form with the server before submitting.
Hete the example is a registration form, where we'll validate the existance of the entered username, if the username already exists we'll show an alert else, proceed with form submission.

The HTML code:
HTML Code:
 <html>
 JavaSrcipt Form Validation<head>
 <script language="JavaScript" type="text/javascript">
 function RemoteRequestObject()
 {
 	var A = false;
 	
 	try
 	{
 		A = new ActiveXObject("Msxml2.XMLHTTP");
 	}
 	catch(e)
 	{
 		try
 		{
 			A = new ActiveXObject("Microsoft.XMLHTTP");
 		}
 		catch(err)
 		{
 			A = false;
 		}
 	}
 	
 	if(!A && typeof(XMLHttpRequest) != 'undefined')
 		A = new XMLHttpRequest();
 		
 	return A;
 }
 
 function validateUser(oForm)
 {
 	var x = RemoteRequestObject();
 	
 	oForm.onsubmit = function()
 	{
 		showMessage(oDiv,2);
 		var usr=oForm.elements['usr'].value;
 		var url = "ajax.php?usr="+usr;
 		x.open("GET",url,true);
 		x.onreadystatechange=function()
 		{
 			if(x.readyState == 4 && x.status == 200)
 			{
 				var r = x.responseText;
 				if(r.indexOf("+OK") == 0)
 				{
 					oForm.submit();
 				}
 				else
 				{
 		 	alert("The chosen username is already in use!\nPlease try another!");
 				}
 			}
 		};
 		x.send(null);
 		return false;
 	}
 
 }
 </script>
 </head>
 <body>
 <form name="usr_check" method="post">
 Enter email : <input type="text" name="usr" />
 
 <input type="submit" value="Check & Submit" />
 </form>
 <script language="JavaScript">
 new validateUser(document.forms['usr_check']);
 </script>
 </body>
 </html>
The PHP code:
PHP Code:
<?
 require_once("../config.inc.php");
 opendb();
 header("Cache-Control: no-cache, no-store, must-revalidate");
 if(isset($_GET['usr']))
 {
     $usr = trim($_GET['usr']);
     $sql = "SELECT * FROM users WHERE usr = '$usr'";
     $result = mysql_query($sql) or die(mysql_error());
 
     if(mysql_num_rows($result)>0)
     {
         echo "+OK";
     }
     else
     {
         echo "-ERR";
     }
 }
 ?>
Hope this code snippet is useful.
shabbir like this
0
perrohunter's Avatar, Join Date: May 2006
Newbie Member
Can you explain us ! !

I dont know the opendb() function

and its not working either :P

thanks :P
0
pradeep's Avatar, Join Date: Apr 2005
Team Leader
I am really sorry not to include the code of the opendb() function. What the function does is opening a connection to the database. I am including the code below, in case you face any more problem please let me know.

Code: php
function opendb()
 {
   global $server,$user,$pass,$db;
   mysql_connect($server,$user,$pass);
   mysql_select_db($db);
 }
 
 function closedb()
 {
   mysql_close();
 }
0
perrohunter's Avatar, Join Date: May 2006
Newbie Member
You think its possible to make a onblur action that send the field over the thing and then send us back a response ?

for example , (taken the idea from invison forums) , when im registering a new user, as soon as he/she release the field ( onblur ) i want to send the info and get a response back to see if the username is right :/

any ideas ?
0
pradeep's Avatar, Join Date: Apr 2005
Team Leader
Yes, its possible to do that.
Call the remote request function when the text field loses focus.
Something like this..

Code: JavaScript
function CheckUser(username)
 {
    //... do the checking here..return true if exists
 }
 
 inputfield.onBlur=function()
 {
    if(CheckUser(this.value))
    {
       alter("This username already exists");
     }
 }

Happy coding!
0
perrohunter's Avatar, Join Date: May 2006
Newbie Member
this sounds strange

inputfield.onBlur=function()


checking the username would mean that u need java to deliver the username to php so php can check it and then give the answer to javascript right ?

we could send the username trou the get so far, how can we get an answer ?

or how could we only post/get the username with out submiting the whole script ?

thanks XD
0
pradeep's Avatar, Join Date: Apr 2005
Team Leader
You need to use a XMLHttp request to send the data - using either GET or POST - and also receiving the answer.
Have a look and the first post of this thread to get an idea how to use the XMLHttp object to validate data remotely, without submitting the current form. Also try googling

Happy Coding!
0
perrohunter's Avatar, Join Date: May 2006
Newbie Member
thanks for all ur answers !

Ya I have already read something abourt xmlhttp on developer.apple.com :P

So far it sounds scary :S

I belife theres a way to halfpost the thing with java script , ill keep researching and post my results here ! ! !
0
jhon.312020's Avatar, Join Date: Jun 2007
Newbie Member
Hi pradeep..

I read ur forums related to ajax php and ajax script..

I have some doubts in your codings please help me out.

I am new to it...

what is meant by show message..

whether i need any extra codings to run it ...

Cheers

jhon
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
jhon, Why not have the discussion of the other article in there only.