Calling Javascript Validation Function Before Submiting And Calling Servlet
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.
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>
Post a Comment for "Calling Javascript Validation Function Before Submiting And Calling Servlet"