Solved

is the Javascript 'onSubmit'  the right event for form validation (client side validation)?

Posted on 2008-10-14
8
709 Views
Last Modified: 2012-06-27
Thought the script appears to be working, form stills submits. I want to make sure the form validates before submitting to server, is the 'onsubmit' the right event to validate in the client side?
<html>

<head>

<title>Validator</title>

<script type="text/javascript">

 function checkForm(form) {

  var valid = true; 

  //first make sure none of the text/password fields are blank

  for (var i = 0; i < form.elements.length; i++) {

      if (form.elements[i].type == "text" || form.elements[i].type == "password")

         {

         form.elements[i].style.backgroundColor="";

           document.getElementById(form.elements[i].name+"_err").innerHTML = ""; 

           if( form.elements[i].value == "") 

         {

            form.elements[i].style.backgroundColor="beige";

            document.getElementById(form.elements[i].name+"_err").innerHTML = "missing value";

            valid = false;

           }

       }

   } 

       //then compare the pwd fields

      if(form.pwd.value != form.pwd2.value)

         { 

          form.pwd.style.backgroundColor="beige";

          form.pwd2.style.backgroundColor="beige";

            document.getElementById("pwd_err").innerHTML = "Pasword values must match";

            valid = false;     

      }

   return valid;

}

</script>

</head> 

<body>

<form onsubmit="return checkForm(this)">

Please enter all requested information:<br>

First Name:<input type="text" name="firstName"><span id="firstName_err"></span><br>

Last Name:<input type="text" name="lastName"><span id="lastName_err"></span><br>

Password:<input type="password" name="pwd"><span id="pwd_err"></span><br>

Password verify:<input type="password" name="pwd2"><span id="pwd2_err"></span><br> 

<input type="submit">

</form>

</body>

</html>

Open in new window

0
Comment
Question by:epifanio67
  • 4
  • 4
8 Comments
 
LVL 7

Expert Comment

by:bluV11t
ID: 22712417
onSubmit is the perfect place for javascript validation, I use it all the time.

Tested your code in FF 3.0.3 and IE 8 and it does not submit until form is correct. Added method="post" to the form and response.write of request.form (ASP / VBScript code so response.write codeline might not work for you, just remove this.) just to be absolutely sure the form doesn't submit.

<html>

<head>

<title>Validator</title>

<script type="text/javascript">

 function checkForm(form) {

  var valid = true; 

  //first make sure none of the text/password fields are blank

  for (var i = 0; i < form.elements.length; i++) {

      if (form.elements[i].type == "text" || form.elements[i].type == "password")

         {

         form.elements[i].style.backgroundColor="";

           document.getElementById(form.elements[i].name+"_err").innerHTML = ""; 

           if( form.elements[i].value == "") 

         {

            form.elements[i].style.backgroundColor="beige";

            document.getElementById(form.elements[i].name+"_err").innerHTML = "missing value";

            valid = false;

           }

       }

   } 

       //then compare the pwd fields

      if(form.pwd.value != form.pwd2.value)

         { 

          form.pwd.style.backgroundColor="beige";

          form.pwd2.style.backgroundColor="beige";

            document.getElementById("pwd_err").innerHTML = "Pasword values must match";

            valid = false;     

      }

   return valid;

}

</script>

</head> 

<body>

<%

response.Write request.Form

 %>

<form onsubmit="return checkForm(this)" method=post>

Please enter all requested information:<br>

First Name:<input type="text" name="firstName"><span id="firstName_err"></span><br>

Last Name:<input type="text" name="lastName"><span id="lastName_err"></span><br>

Password:<input type="password" name="pwd"><span id="pwd_err"></span><br>

Password verify:<input type="password" name="pwd2"><span id="pwd2_err"></span><br> 

<input type="submit">

</form>

</body>

</html>

Open in new window

0
 

Author Comment

by:epifanio67
ID: 22713209
Thx blue11t

for some odd reason it is not validating for me... let me ask you:

in the function checkForm(form)

instead of (form) shouldn't this be (name_of_form)?

<form onsubmit="return checkForm(this)" method="post" name="name_of_form">


Thx,
0
 
LVL 7

Expert Comment

by:bluV11t
ID: 22713927
If you pass "name_of_form" (you should actually use ID of form) to the function you need to use document.getElementById('id_of_form') to reference the form in your function. You're passing the entire form object itself to the function.

You could also try using getElementById throughout the javascript code or

<form onsubmit="return checkForm(document.getElementById('id_of_form'));" method="post" name="name_of_form">


0
 

Author Comment

by:epifanio67
ID: 22715382
thx bluV11t

below is the actual script; when I click onsubmit leaving the fields blank, the error msg appear for a fraction of a sec, then disappears..... I need that error msg to display after clicking onsubmit...
<style type="text/css">
 

label, label span {display: block; padding-bottom: .5em;}

label {float: left; width: 100%;}

label span {float: left; width: 25%; text-align: right; color: #333333; text-transform: uppercase;}
 

fieldset {float: left; width: 500px; margin-bottom: 0 20px 10px 0; padding: 20px; border: 1px solid #dddddd; overflow: hidden;}

fieldset input {display: block; float: left; width: 35%; border: 1px solid #dddddd;}

fieldset input:hover {border: 1px solid #9e1110;}

fieldset input:active {float: left; width: 35%; border: 1px solid #9e1110;}

fieldset input:focus {float: left; width: 35%; border: 1px solid #9e1110;}
 

fieldset div.button {clear: both; float: right; margin-bottom: 20px; padding: 10px 20px; border: 0px solid #dddddd; text-align: center;}

fieldset div.button input {width: 	100%; padding: 0.25em; background-color: #dddddd; border: 2px double #cccccc; border-top-color: #9e1110; font: 92% tahoma, verdana, arial, sans-serif; color: #fff; text-transform: uppercase; }

fieldset div.button input:hover  { width: 100%; background-color: #333333; }

fieldset div.button input:active {width: 100%; background-color: #333333;}

fieldset div.button input:focus  {width: 100%; background-color: #333333;}
 

</style>
 
 

<script type="text/javascript" language="javascript" >
 

function checkForm(form) {
 

   var valid = true;
 

   for (var i = 0; i < form.elements.length; i++)  

   {

   		if (form.elements[i].type == "text") 

   		{

   			form.elements[i].style.backgroundColor="";

   			document.getElementById(form.elements[i].name+"_err").innerHTML = ""; 
 

        	if( form.elements[i].value == "") 

        	{

        		form.elements[i].style.backgroundColor="gold";

        		document.getElementById(form.elements[i].name+"_err").innerHTML = "Must provide a value";

				valid = false;

			}

      	}

   }

   

   if(form.password.value != form.password2.value)

   { 

     form.password.style.backgroundColor="gold";

     form.password.style.backgroundColor="gold";

     document.getElementById("password_err").innerHTML = "Pasword values must match";

     valid = false;     

   }

   return valid;

}
 

</script>
 
 
 

<center>

<form id="regForm" 

		onSubmit="return checkForm(this)"

		name="regForm" 

		action="" />
 

 <fieldset>

  <label for="name"><span><?php echo 'Name'; ?></span>

   <input type="text" name="name" id="name" size="40" 

   			value="" 

   			maxlength="50" /> 

   <span id="name_err"></span>

  </label>

  

  <label for="username"><span><?php echo 'Username'; ?></span>

   <input type="text" name="username" id="username" size="40" 

   			value="" 

   			maxlength="50" /> 

   <span id="username_err"></span>

   </label>

  

  <label for="email"><span><?php echo 'eMail'; ?></span>

   <input type="text" name="email" id="email" size="40" 

   			value=""

   			maxlength="50" />

   <span id="email_err"></span>

  </label>

  

  <label for="password"><span><?php echo 'Password'; ?></span>

   <input type="text" name="password" id="password" size="40" 

   			value=""

   			maxlength="50" />

   <span id="password_err"></span>

   </label>

  

  <label for="password2"><span><?php echo 'Verify Password'; ?></span>

   <input type="text" name="password2" id="password2" size="40" 

   			value=""

   			maxlength="50" />

   <span id="password_err"></span>

   </label>

 

 <div class="button">

	<input type="submit" value="<?php echo 'SUBMIT'; ?>" />

 </div>

  

 </fieldset> 

<input type="hidden" name="option" value="<?php echo $option; ?>" />

<input type="hidden" name="task" value="register" />

<input type="hidden" name="Token" value="1" />

</form>

</center>

Open in new window

0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:epifanio67
ID: 22715387
thanks for all your help.... losing my mind here...
0
 
LVL 7

Expert Comment

by:bluV11t
ID: 22716075
Errors in your javascript.

Lines 33 and 38
document.getElementById(form.elements[i].name+"_err").innerHTML = "";
document.getElementById(form.elements[i].name+"_err").innerHTML = "Must provide a value";



There are no elements in your sorce with name ending with "_err".... Are you missing some labels perhaps?
Add an _err element for each of the elements your trying to validate.

0
 
LVL 7

Accepted Solution

by:
bluV11t earned 125 total points
ID: 22716144
My mistake, you are actually just missing password2_err (typo prob., you've got two password_err span's)...
0
 

Author Closing Comment

by:epifanio67
ID: 31506280
thx you bluv11t.... that fixed the issue.... in this coding world one thing can through you off... thx for all your help
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now