Form validation with PHP & JavaScript

Discussion in 'PHP' started by pradeep, Sep 5, 2005.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    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:
    <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:
     <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:
    <?
     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 likes this.
  2. perrohunter

    perrohunter New Member

    Joined:
    May 7, 2006
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Can you explain us :D ! !

    I dont know the opendb() function :(

    and its not working either :P

    thanks :P
     
  3. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    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.

    PHP:
    function opendb()
     {
       global 
    $server,$user,$pass,$db;
       
    mysql_connect($server,$user,$pass);
       
    mysql_select_db($db);
     }
     
     function 
    closedb()
     {
       
    mysql_close();
     }
     
     
  4. perrohunter

    perrohunter New Member

    Joined:
    May 7, 2006
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    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 ?
     
  5. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Yes, its possible to do that.
    Call the remote request function when the text field loses focus.
    Something like this..

    Code:
     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!
     
  6. perrohunter

    perrohunter New Member

    Joined:
    May 7, 2006
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    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
     
  7. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    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!
     
  8. perrohunter

    perrohunter New Member

    Joined:
    May 7, 2006
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    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 ! ! !
     
  9. jhon.312020

    jhon.312020 New Member

    Joined:
    Jun 29, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    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:
     
  10. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    jhon, Why not have the discussion of the other article in there only.
     
  11. jhon.312020

    jhon.312020 New Member

    Joined:
    Jun 29, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    sir i read the forum of username validation using php ajax and javascript.


    The code which u gave was interesting...

    But i tried out in my system...

    It is not reporting anything about username whether it is availabe or not..

    I would not trace out the error also..

    with cheers
    jhon
     
  12. jhon.312020

    jhon.312020 New Member

    Joined:
    Jun 29, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    sure v ll have say it... :eek:
     
  13. daljit

    daljit New Member

    Joined:
    Aug 14, 2007
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    oForm.onsubmit = function()
    {
    showMessage(oDiv,2);
    var usr=oForm.elements['usr'].value;
    var url = "ajax.php?usr="+usr;

    showMessage(oDiv,2); what about this function ??
    How do it show message??
    thanks for replying.
    DS
     
  14. daljit

    daljit New Member

    Joined:
    Aug 14, 2007
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    No prob!!
    ShowMessage(oDiv,2) function works now.
    DS
     
  15. clocking

    clocking New Member

    Joined:
    Jun 12, 2007
    Messages:
    122
    Likes Received:
    0
    Trophy Points:
    0
    hi!
    I saw your article. It's useful. So, follow you,May Use PHP and Mysql more useful?
    thanks so much! :)
     
  16. gkumar

    gkumar New Member

    Joined:
    Jun 16, 2009
    Messages:
    58
    Likes Received:
    5
    Trophy Points:
    0

    Javascript Form Validation:-
    Here is the sample source code of the above demo
    Code:
    <html>
    <head>
    <title>Javascript Form Validation</title>
    <script language='JavaScript' type='text/JavaScript'>
    <!--
    function validate() {
    	if(document.form1.textinput.value=='')
    		{
    		alert('Fill the Input box before submitting');
    		return false;
    		}
    	
    	else	{
    		return true;
    			}
    }
    //-->
    </script>
    </head>
    <body>
    <form name='form1' action='javascript_validation.php' method='post' 
    				onSubmit='return validate();'>
    Input :<input type=text name=textinput value=''>
    <input type=submit value=submit>
    </form>
    </body>
    </html>
    
    PHP Form Validation:-In the PHP form creation page, the following line was used to start the form.
    Code:
    <form name="addLink" onSubmit="return checkForm(this);" action="addurl.php" method="POST">
    This line invokes a JavaScript routine which is contained in the HTML header part of the page. If this routine returns with a successful status, the action item is called which means that "addurl.php" is called and data from the form is passed to it. Sessions are not required to pass this data to the addurl.php file and the names of values created on the form page will be available. These values include:
    * title
    * description
    * uname
    * email
    * stype
    * category
    This JavaScript function will check to be sure there is a URL, title, link description, and category entered.

    Code:
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    function checkForm(TheForm) {
      // url, title, description
      if (TheForm.url.value.length == 0) {
       TheForm.url.value = prompt("You forgot to enter the link URL for addition!");
       return false;
      }
      if (TheForm.title.value.length == 0) {
       TheForm.title.value = prompt("You forgot to enter the link title for addition!");
       return false;
      }
      if (TheForm.description.value.length == 0) {
       TheForm.description.value = prompt("You forgot to enter the link description for addition!");
       return false;
      }
      if (TheForm.category.value.length == 0) {
       TheForm.category.value = alert("You forgot to enter the category!");
       return false;
      }
      return true;
    }// end function checkalForm
    // -->
    </SCRIPT>
     
    shabbir likes this.
  17. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    [COMMENT]gkumar its code blocks [​IMG] and not quote [​IMG] for code snippets.[/COMMENT]
     
    Last edited: Jan 21, 2017
  18. gkumar

    gkumar New Member

    Joined:
    Jun 16, 2009
    Messages:
    58
    Likes Received:
    5
    Trophy Points:
    0
    Javascript Form Validation:-
    We can validate the entry of any form by using JavaScript. This is a client side JavaScript form validation and you can check server side php form validation also. Before taking up any client side validation it is advisable to check JavaScript is not disabled in the client browser.

    You can see a demo of Form Validation here.

    Notice how you are prevented from submitting form unless the text input field is filled.

    Here is the sample source code of the above demo
    Code:
    <html>
    <head>
    <title>Javascript Form Validation</title>
    <script language='JavaScript' type='text/JavaScript'>
    <!--
    function validate() {
    	if(document.form1.textinput.value=='')
    		{
    		alert('Fill the Input box before submitting');
    		return false;
    		}
    	
    	else	{
    		return true;
    			}
    }
    //-->
    </script>
    </head>
    <body>
    <form name='form1' action='javascript_validation.php' method='post' 
    				onSubmit='return validate();'>
    Input :<input type=text name=textinput value=''>
    <input type=submit value=submit>
    </form>
    </body>
    </html>
    
    Form validation with PHP:-

    Let’s talk about form validation. Here’s what I would class as the ideal validation system for a form in a web application:

    1. The form is displayed; you fill it in.
    2. You submit the form to the server.
    3. If you missed something out or provided invalid input, the form is redisplayed pre-filled with the valid data you already entered.
    4. The redisplayed form tells you what you got wrong. It also flags the fields that were incorrect.
    5. Loop until you fill the form in correctly.

    Writing this once in PHP is trivial, but takes quite a bit of very dull code. Writing this for more than one form quickly becomes a tedious nightmare of duplicating and slightly editing code, which is why so few forms bother.

    I’ve been trying to figure out an elegant way of automating as much of this code as possible on and off for more than two years. I’ve tried systems that generate the whole form based on a bunch of criteria (too inflexible), systems that describe the validation rules (fine but they don’t help with the redisplay logic) and I’ve looked at solutions available in other language (such as ASP.NET), all to no avail. Over the past couple of days I’ve been working on the problem again, and for the first time I think I’m actually getting somewhere.

    My latest attempt (sparked by this article on Evolt) involves embedding validation and redisplay rules in the markup of the form itself. The form is written in XHTML, but with a number of additional tags and elements. Any form field elements can have a number of additional attributes which specify the validation rules of the form. For example:


    Code:
    <input type="text" name="name" 
      compulsory="yes" validate="alpha" callback="uniqueName" 
      size="20" />
    The highlighting in the above line marks the additional elements. In this case, they mean that the field is compulsory, must contain only letters, and should be checked for final validity by calling the user defined uniqueName() function.

    There are a few other validation attributes, but the above gives a good idea of how the system works. The second problem is how to display errors. Part of the solution here is my custom <error> element, which can be used to associate an error message with an error in a particular field. In my tests I’ve been using this to display an exclamation mark next to invalid fields:

    Code:
    <input type="text" name="name" 
      compulsory="yes" validate="alpha" callback="uniqueName" 
      size="20" />
    <error for="name"> !</error>
    
    This associates the text inside the <error> element (in this case the single exclamation mark) with the “name” field.

    So far, all I’ve done is add a bunch of invalid markup to an otherwise valid chunk of XHTML. The key is how this markup is processed. FormML (for want of a better name) is never passed to the browser; instead it is processed by my PHP FormProcessor class before being displayed. This class strips out all of the FormML tags, and also applies logic to the rest of the form based on the information from the tags. Because the whole thing is XHTML, this can be relatively easily achieved using PHP’s built in XML parser. The XML is modified on the fly to create the XHTML that is sent to the browser. In the above example, the contents of the <error> element would only be displayed if the form was being redisplayed and the user had not filled in their name correctly. In addition, the class populates the value attribute of each input element with the previously entered data and adds an “invalid” class to the element to allow it to be styled appropriately.

    The next problem is to display a list of descriptive error messages describing the problem. This took slightly longer to work out: I needed a way of setting an error message for each potential problem (remember there are several ways a field can be invalid: it could have been left unfilled, or it could have failed a regular expression check, or it could have failed a callback function), and I also needed some way of indicating how these errors should be displayed. My eventual solution was to introduce a new <errormsg> element for specifying error messages, and a simple templating system (based on a few more custom tags) for indicating where these errors should be displayed. I’m not entirely happy with the way this works at the moment, but here’s what I’m using:

    Code:
    errorlist>
    <ul>
    <erroritem> <li><message /></li></erroritem>
    </ul>
    </errorlist>
    <errormsg field="name" test="compulsory">You did not enter your name</errormsg>
    <errormsg field="name" test="alpha">Your name must consist <em>only</em> of letters</errormsg>
    The <errormsg> elements can be placed anywhere in the markup, and will be removed before display. The <errorlist> fragment defines the template for the list of error messages, with the <erroritem> element enclosing the “template” for each error and the <message> element showing where the actual error message (as defined elsewhere) should be displayed. Note that the <errormsg> elements specify the field and the test that they relate to. It is not necessary to provide custom error messages for every possible field/test combination; the system generates moderately intelligent error messages in the event that one has not been provided.

    That’s a lot of custom markup to define the behaviour of a form. The good news is that the actual PHP used to display, validate and redisplay the form is incredibly simple. Here it is:
    Code:
    $formML = '... formML XML code goes here ...';
    $processor = new FormProcessor($formML);
    if ($processor->validate()) {
        // The form has been submitted and is valid - process the data
        echo 'Form data is OK!';
    } else {
        // This will display the form for the first time OR redisplay it
        // with relevant error messages
        $processor->display();
    }
    And that’s all there is to it.

    The code is still under very heavy development. At the moment it’s messy, has several minor bugs (and possibly some major ones I haven’t yet uncovered), isn’t fully tested and is almost certainly not ready for deployment. Never-the-less, you can play with a demo form that uses it or grab the code here:

    * FormProcesser.class.php—the class(es)
    * test.php—the demo form, as seen here.

    Incidentally, I haven’t mentioned javascript in the above in an attempt to keep things simple. I know client side validation is a great addition to stuff like this (provided it’s backed up by solid server side logic) and one of my longer term aims is to dynamically add the necessary javascript to the form during the processing phase, thus skipping the need to write any boring validation code by hand.
     
  19. nwndm

    nwndm New Member

    Joined:
    Sep 7, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    In response to pradeep's Initial Code:

    You must switch the following code snippets in your PHP file:
    Code:
    if(mysql_num_rows($result) > 0)
        {
            echo "-ERR";
        }
        else
        {
            echo "+OK";
        }
    

    This is because you WANT PHP to call out an error if you have one or more results because this means you have that user name taken already in the database. If you don't have any results, you may create that username successfully, thus echo "+OK";

    So this condition is met now:
    Code:
    if(r.indexOf("+OK") == 0)
                     {
                         oForm.submit();
                     }
    
    the form is then submitted, otherwise you get the alert code snippet.

    Tested my code to make sure.
     
  20. amyfex20

    amyfex20 New Member

    Joined:
    Jul 18, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I know how to submit records on a form to a database using PHP, but I don't know the php code for view, update and delete of records.
    please do send it to my email: amyfex@gmail.com
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice