Form Validation Javascript with JSP


We have discussed lot about JSP, JSP is server side scripting language as we know, but when we do practical real world programming we need more than JSP.
Suppose we have an html form (Html form contain only html tags, No JSP code) having username text field, and password field. Before submitting page to web server, it should be validate HTML field data. This validation can be done on client side instead directly to server. It should be done on client side, because it is very faster than server validation. If user data is not of specified range of standard validation program, it should show error at client browser of user. This form will not jump to action page (server) until it fully validated.

Let’s see in example

formValidation.jsp



<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<html>
<head>
<script>
function validateForm()
{
    if(document.frm.username.value=="")
    {
      alert("User Name should be left blank");
      document.frm.username.focus();
      return false;
    }
    else if(document.frm.pwd.value=="")
    {
      alert("Password should be left blank");
      document.frm.pwd.focus();
      return false;
    }
}
</script>
</head>
<body>
<form name="frm" method="get" action="validateInput.jsp" onSubmit="return validateForm()">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="22%">&nbsp;</td>
    <td width="78%">&nbsp;</td>
    </tr>
  <tr>
    <td>UserName </td>
    <td><input type="text" name="username" /></td>
  </tr>
  <tr>
    <td>Password</td>
    <td><input type="text" name="pwd" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><input type="submit" name="submit" value="Submit"></td>
    </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    </tr>
</table>
</form>
</body>
</html>

When we submit this form to web server, first it will check and validate. onSubmit="return validateForm()" event check validateForm() function in javascript, and if any field find blank it will throw error alert on browser. This submit only when validateForm() function return true. This results in jump to next form validateInput.jsp of JSP page.


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email