Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Form validation with PHP & JavaScript (http://www.go4expert.com/articles/form-validation-php-javascript-t438/)

pradeep 5Sep2005 12:35

Form validation with PHP & JavaScript
 
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.

perrohunter 7May2006 07:08

Re: Form validation with PHP & JavaScript
 
Can you explain us :D ! !

I dont know the opendb() function :(

and its not working either :P

thanks :P

pradeep 8May2006 10:45

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();
 }


perrohunter 9May2006 06:51

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 ?

pradeep 9May2006 10:29

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!

perrohunter 10May2006 01:55

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 :D :D :D :D :D

pradeep 10May2006 11:22

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!

perrohunter 11May2006 01:16

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 :D ! ! !

jhon.312020 29Jun2007 19:26

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 :confused:

shabbir 29Jun2007 22:15

Re: Form validation with PHP & JavaScript
 
jhon, Why not have the discussion of the other article in there only.


All times are GMT +5.5. The time now is 08:45.