Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The JavaScript FAQ
Prev Home Next

Validating a Form

Question: How do I validate the form input before sending it to the server?

Answer: To validate the form input, call your validation function from the form's onSubmit event handler. When the user submits the form, the browser will first invoke the onSubmit event handler. The form will actually be submitted to the server only if the handler returns true. In the following example, the onSubmit event handler validates the user's email address. (For simplicity, the address is considered to be valid if it does not contain spaces, contains the @ character and if @ is neither the first nor the last character.) Note that the handler itself must contain a return statement in order to return the value true or false to the browser.

Your email:
This example used the following code:
<script language="JavaScript">
<!--
function isValid() {
 var email=document.form1.t1.value;
 if (email.indexOf(' ')==-1 
      && 0<email.indexOf('@')
      && email.indexOf('@')+1 < email.length
 ) return true;
 else alert ('Invalid email address!')
 return false;
}
//-->
</script>

<form name=form1 
method=post
action="javascript:alert('The form is submitted.')" 
onSubmit="return isValid()">
Your email:
<input type=text name=t1 size=20 >
<input type=submit value=Submit>
</form>

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

The JavaScript FAQ
Prev Home Next


 
 
  Mirrored with kind permission of Alexei Kourbatov Design by Interspire