Tims Servlet Tutorial

Tutorial Home

  1. What are servlets ?
  2. The Hello World Servlet
  3. Running Servlets
  4. Reading Form Data
  5. Servlet Configuration
  6. Client Side Form Validation
  7. Cookies
  8. Sessions
  9. Authentication
  10. Dynamic Images
  11. Design, Testing, Security
  12. Servlets and Apache
  13. Using Servlets in SOCS

Client Side Form Validation


Most non-trivial servlets will probably need to perform some kind of validation on the data submitted in a form. At the simplest level, this could simply be a check that the user has actually entered something in all of the form boxes. If this kind of validation takes place in the servlet, the user would has to submit the form and download a response before they can find out if their were any errors. This is not a very efficient use of network bandwidth (especially if the user is working via a modem and the form page is quite large) or server time.

For simple validation work, JAVASCRIPT code can be embedded into an HTML page to perform simple validation work client-side, before the form data is transmitted across the internet and alert the user to any problems. Below is a modified form which can be used with the myNameServlet to check that the user has entered some text before submitting it to the servlet. The servlet itself is unchanged.



<HTML>
<HEAD>
<script language="javascript">

    <!--
      function validateForm()
      {
        if (document.entryForm.yourname.value=="")
        {
          alert("You haven't entered your name !");
          return false;
        }

        document.entryForm.submit();
        return true;
      }
  // -->

</script>
</HEAD>
<BODY>

<FORM METHOD=POST ACTION="/servlets/demoServlets.MyNameServlet" NAME="entryForm">
<INPUT TYPE="TEXT" SIZE="30" NAME="yourname">
<INPUT TYPE="BUTTON" VALUE="  Submit  " OnClick="validateForm()">
</FORM>

</BODY>
</HTML>


You can try out the new form here. Just click submit without entering any text in the box and see what happens


This technique is quite general and can be used with CGI-Scripts, JSP's or any other webserver technology that works with HTML forms.

Note : Whilst Javascript is very useful, your back end servlets should not rely on javascript checking to ensure the validity of the information being submitted and to stop users doing things they shouldn't. Always re-check submitted data if there is a security/data integrity implication to the requested function. Malicious users can easily bypass Javascript checks !


<< Previous Page | Next Page >>




Tims Home Page       |       Page last modified : 02 April 2007