Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

My form still submits even though I validate it.

Validation

My form still submits even though I validate it.

by  HellTel  Posted    (Edited  )
A very common problem, this one.
On submission of a form, many people like to call a function to validate some data and then not submit the form if validation fails. What most people tend to forget is to return the function called from the <form> tag. If this is forgotten, the form will still submit. So here is an example that will only submit if you enter the word "correct" into the text field.

Code:
<html>
<head>
<script language="javascript">
function validateData(){
  if (document.getElementById("txt").value != "correct"){
    alert('That is not correct, please try again');
    return false;  // if false is returned, the form action will not take place and the form won't submit
  } else {
    alert('That is correct, form will submit');
    return true;  // if true is returned, the form action will take place and the form has been submitted
  }
}
</script>
</head>

<body>
<form id="theForm" method="post" onSubmit="return validateData()" action="javascript:alert('It has submitted')"> 
<!-- Note the return in the onSubmit above, that is VERY important -->
<input id="txt" type="text"><br>
<input type="submit">
</form>
</body>

</html>
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top