Calling javascript validation function before submiting and calling servlet

11,877

Solution 1

Change your javascript function as follows,

function validateForm(event)
{
    event.preventDefault(); // this will prevent the submit event.
    if(document.loginform.username.value=="")
    {
      alert("User Name can not be left blank");
      document.loginform.username.focus();
      return false;
    }
    else if(document.loginform.password.value=="")
    {
      alert("Password can not be left blank");
      document.loginform.password.focus();
      return false;
    }
    else {
        document.loginform.submit();// fire submit event
    }
}

Also, pass the submit event in the function call like this,

<form name="loginform" action="login" method="post" onSubmit="return validateForm(event);">

the approach provided by Crowder is good, but you might also have to handle the submit event being fired anyway if the validation fails.

DEMO FIDDLE

Solution 2

You're using document.frm to refer to your form, but your form's name is loginform, not frm. So you want document.loginform if you want to rely on the automatically-created document properties.

I prefer not to rely on them. Instead, you might pass the form reference into your validation function:

<form ... onSubmit="return validateForm(this);" ...>

...and then use the argument in your function:

function validateForm(frm)
{
    if(frm.username.value=="")
    {
      alert("User Name can not be left blank");
      frm.username.focus();
      return false;
    }
    else if(frm.pwd.value=="")
    {
      alert("Password can not be left blank");
      frm.password.focus();
      return false;
    }
}

(Of course, there I'm still relying on automatic properties, in this case on the form object. If I wanted to really avoid them, I could use frm.querySelector("[name=username]") for the username field and frm.querySelector("[name=password]") for the password field. All modern browsers, and IE8, have querySelector. But at least only relying on the ones on the form is a bit more contained than worrying about everything that gets dumped on document.)

Here's your form and the code above in a snippet, with the action modified to take you to google.com (and the method modified to GET; both of those mods are just for the demo): Try it with a blank username or password, and you'll note that the form does not submit:

function validateForm(frm)
{
  if(frm.username.value=="")
  {
    alert("User Name can not be left blank");
    frm.username.focus();
    return false;
  }
  else if(frm.pwd.value=="")
  {
    alert("Password can not be left blank");
    frm.password.focus();
    return false;
  }
}
<form name="loginform" action="http://google.com/search?q=kittens" method="get" onSubmit="return validateForm(this);">
<p> Enter user name: <input type="text" name="username"><br>
Enter password: <input name="password" type="password"><br> 
<input type="submit">
</p>
</form>
Share:
11,877
user3607625
Author by

user3607625

Updated on June 16, 2022

Comments

  • user3607625
    user3607625 almost 2 years

    I am trying to validate the form and after that calling a servlet and it fails because form doesn't validete. I' ve pasted some code below. Could you give me some tips and help with this issue?

    function validateForm()
    {
        if(document.frm.username.value=="")
        {
          alert("User Name can not be left blank");
          document.frm.username.focus();
          return false;
        }
        else if(document.frm.pwd.value=="")
        {
          alert("Password can not be left blank");
          document.frm.password.focus();
          return false;
        }
    }
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <link href="/LoginExample/css/style.css" rel="stylesheet" type="text/css" />
    <script language="JavaScript" type="text/JavaScript" src="/LoginExample/js/validation.js"></script>
    <title>Login example</title>
    </head>
    <body>
    <form name="loginform" action="login" method="post" onSubmit="return validateForm();">
    <p> Enter user name: <input type="text" name="username"><br>
    Enter password: <input name="password" type="password"><br> 
    <input type="submit">
    </p>
    </form>
    
    <a href="register.jsp"><input type="button" value="register" name="Sign in"></a>
    
    </body>
    </html>
  • Shoaib Chikate
    Shoaib Chikate over 9 years
    About to gave same answer. But now don't want to duplicate the answer.His way of calling his form is wrong. Good catch
  • user3607625
    user3607625 over 9 years
    T.J. Crowder thank you very much for your help! It is almost that what I wanted but there is still one issue to deal with. When I left username blank I get a message so it's being validating but after that leaving empty username textbox servlet is being called. Can you help me with this?
  • T.J. Crowder
    T.J. Crowder over 9 years
    @user3607625: It shouldn't be, not with the code you've shown. I've added a snippet to demonstrate.
  • user3607625
    user3607625 over 9 years
    Still the same problem. After validating it redirects me to servlet.
  • VPK
    VPK over 9 years
    Have you checked the fiddle?
  • rnyunja
    rnyunja about 6 years
    This works! Blocking submit provides value by allowing you to validate the form driven by a servlet before submit. Once you submit, the servlet takes over to redirect the uri via RequestDispatcher and you cannot control validation then
  • VPK
    VPK about 6 years
    @rnyunja, you are right, that's why preventDefault is useful and form is submitted only when client-side validations are cleared. But we shouldn't depend entirely on client-side validations only. ;)