Jump to content

Validate form


alexAAA
 Share

Recommended Posts

HelloIs there a way I cancheck multiple functions with a onsubmit Here's about how I did it (it's not the whole code as I am not on my pc but that's about what I did): Javascript:

function validName() {if(document.frm_reg.name.value.length < 1) {//some onkeyup code...return false;} else{return true;}}function validMail() {if(....) {return false;} else{return true;}}function checkForm() {if(validName() && validMail()) {return true;} else {return false;}}

HTML:

<form><input type="text" name="name" id="name" onkeyup="validName();"/>//here are some other input tags...<input type="submit" onsubmit="return checkForm();" value="Register"></form>

Thanks!

Link to comment
Share on other sites

If you just want to see how they're working use an alert? If not, how do you want to check them?

Link to comment
Share on other sites

I checked them by changing the color of the field using the onkeyup()-function, which works fine (it's just not in the code because I'm not at my pc at the moment). But I also want the form not to be sent if there is an error so when I hit the submit button it should again go through all the functions and determine wheter all fields are filled in correctly.That' why I created the function checkForm() which should check if every function returns true.Only if that is the case the form should be submitted.

Link to comment
Share on other sites

The onsubmit is placed in the form element, never the submit button, heres an example to check all text inputs

<form action="#" method="post" id="myform" name="myform" onSubmit="return validate_this_form(this)"> <input id="fname" name="fname" type="text" title="First Name" /><input id="lname" name="lname" type="text" title="Last Name" /><input id="email" name="email" type="text" title="Email Address" /><input id="address" name="address" type="text" title="Address" /> <input type="submit" value="Submit Button"  /></form>

function validate_this_form(form_elem){var parent_form=document.getElementById(form_elem.id);valid=true; var errormessage=""; for (i=0;i<parent_form.elements.length;i++)	{    if(parent_form.elements[i].type=="text")		{		if(parent_form.elements[i].value==parent_form.elements[i].defaultValue || parent_form.elements[i].value=="")			{			valid=false;			errormessage+= "Please supply "+parent_form.elements[i].title+"\n";			}		}	}if(!valid)	{	alert(errormessage)	}return valid; }

Edited by dsonesuk
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...