Learn how to Make Money Online doing freelancing, Affiliate Marketing, Blogging and many more ...
Go4Expert
Go4Expert RSS Feed

Go Back   Programming and SEO Forum >  Go4Expert > Articles / Source Code > Web Development > PHP

Discuss / Comment  Copy HTML to Clipboard  Copy BBCode to Clipboard  | More
 
Bookmarks Article Tools Search this Article Display Modes

Form validation with PHP & JavaScript


On 5th September, 2005
Form validation with PHP & JavaScript

Show Printable Version Email this Page Subscription Add to Favorites Copy Form validation with PHP & JavaScript link

Author

pradeep ( Team Leader )

Yet to provide details about himself


All articles By pradeep

Recent Articles

Similar Articles

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.
Old 05-07-2006, 07:08 AM   #2
Newbie Member
 
Join Date: May 2006
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
Rep Power: 0
perrohunter is on a distinguished road

Re: Form validation with PHP & JavaScript


Can you explain us ! !

I dont know the opendb() function

and its not working either :P

thanks :P
perrohunter is offline   Reply With Quote
Old 05-08-2006, 10:45 AM   #3
Team Leader
 
pradeep's Avatar
 
Join Date: Apr 2005
Location: Kolkata, India
Posts: 1,470
Thanks: 0
Thanked 35 Times in 30 Posts
Rep Power: 7
pradeep will become famous soon enough
Send a message via Yahoo to pradeep

Re: Form validation with PHP & JavaScript


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();
 }
__________________
Vote for the Most Entertaining Member of 2008

To err is human,to detect is divine!
pradeep is offline   Reply With Quote
Old 05-09-2006, 06:51 AM   #4
Newbie Member
 
Join Date: May 2006
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
Rep Power: 0
perrohunter is on a distinguished road

Re: Form validation with PHP & JavaScript


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 ?
perrohunter is offline   Reply With Quote
Old 05-09-2006, 10:29 AM   #5
Team Leader
 
pradeep's Avatar
 
Join Date: Apr 2005
Location: Kolkata, India
Posts: 1,470
Thanks: 0
Thanked 35 Times in 30 Posts
Rep Power: 7
pradeep will become famous soon enough
Send a message via Yahoo to pradeep

Re: Form validation with PHP & JavaScript


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!
__________________
Vote for the Most Entertaining Member of 2008

To err is human,to detect is divine!
pradeep is offline   Reply With Quote
Old 05-10-2006, 01:55 AM   #6
Newbie Member
 
Join Date: May 2006
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
Rep Power: 0
perrohunter is on a distinguished road

Re: Form validation with PHP & JavaScript


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
perrohunter is offline   Reply With Quote
Old 05-10-2006, 11:22 AM   #7
Team Leader
 
pradeep's Avatar
 
Join Date: Apr 2005
Location: Kolkata, India
Posts: 1,470
Thanks: 0
Thanked 35 Times in 30 Posts
Rep Power: 7
pradeep will become famous soon enough
Send a message via Yahoo to pradeep

Re: Form validation with PHP & JavaScript


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!
__________________
Vote for the Most Entertaining Member of 2008

To err is human,to detect is divine!
pradeep is offline   Reply With Quote
Old 05-11-2006, 01:16 AM   #8
Newbie Member
 
Join Date: May 2006
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
Rep Power: 0
perrohunter is on a distinguished road

Re: Form validation with PHP & JavaScript


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 ! ! !
perrohunter is offline   Reply With Quote
Old 06-29-2007, 07:26 PM   #9
Newbie Member
 
Join Date: Jun 2007
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
Rep Power: 0
jhon.312020 is on a distinguished road

Re: Form validation with PHP & JavaScript


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
jhon.312020 is offline   Reply With Quote
Old 06-29-2007, 10:15 PM   #10
Go4Expert Founder
 
shabbir's Avatar
 
Join Date: Jul 2004
Location: On Earth
Posts: 12,516
Thanks: 53
Thanked 276 Times in 215 Posts
Rep Power: 10
shabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud ofshabbir has much to be proud of
Send a message via Yahoo to shabbir

Re: Form validation with PHP & JavaScript


jhon, Why not have the discussion of the other article in there only.
shabbir is offline   Reply With Quote
Discuss / Comment  Copy HTML to Clipboard  Copy BBCode to Clipboard  | More


Currently Active Users Reading This Article: 2 (0 members and 2 guests)
 
Article Tools Search this Article
Search this Article:

Advanced Search
Display Modes
Bookmarks

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off

Similar Threads / Articles
Thread Thread Starter Forum Replies Last Post
GUestbook in PHP pradeep PHP 1 09-15-2008 08:01 AM
PHP On-The-Fly! Kings PHP 5 05-01-2008 11:28 AM
Track your visitors, using PHP Kings PHP 8 12-11-2006 01:53 AM
PHP and Cookies; a good mix! Kings PHP 1 12-07-2004 08:53 AM
Begining with PHP shabbir PHP 0 07-15-2004 03:22 PM

 

All times are GMT +5.5. The time now is 05:28 AM.