INFO: Validate Data when Submitting Forms with Internet ExplorerID: Q216435
|
This article explains where to validate data when submitting forms. The best option is to validate all the form data in the onSubmit event handler of the form, though there is a catch when using Internet Explorer 3.x. You can also use onChange and onBlur events to validate data. This article points out some things to watch out for when doing so.
<HTML>
<HEAD>
<SCRIPT language="JavaScript">
function ValidateData()
{
if (nameform.namefld.value == "")
{
alert("Please enter your name(25 chars)");
event.returnValue = false
}
//else the form will be submitted automatically
}
</SCRIPT>
</HEAD>
<BODY>
<FORM id=nameform name=nameform onsubmit="ValidateData()" action="http://www.microsoft.com">
<!--
If you're using POST method, make sure your action is set to an .asp file.
If it's a html file, Error 405 will be displayed.
-->
Enter your name : <INPUT type=text id=namefld name=namefld> <BR>
<INPUT type=submit value="Submit Form">
</FORM>
</BODY>
</HTML>
Since Internet Explorer 3.x does not support the event object, the following script can be used to cancel the event.
<HTML>
<HEAD>
<SCRIPT language="JavaScript">
function ValidateData()
{
if (nameform.namefld.value == "")
{
alert("Please enter your name(25 chars)");
nameform.namefld.focus();<BR/>
return false;
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM id=nameform name=nameform onsubmit="return ValidateData()">
Enter your name : <INPUT type=text id=namefld name=namefld> <BR>
</FORM>
<!--
If using VBScript, you can use onSubmit="ValidateData()" and in the VBScript function set the return value to false as in this example:
Function ValidateData
if nameform.namefld.value = "" then
ValidateData = false
End if
End Function
-->
</BODY>
</HTML>
<HTML>
<BODY>
<SCRIPT language="JavaScript">
function ValidateData(){
if ((nameform.namefld.value == "") || (nameform.namefld.value.length < 5))
{
alert("Invalid input");
event.returnValue = false;
}
}
</SCRIPT>
<FORM id=nameform name=nameform action="http://www.microsoft.com">
Enter your name : <INPUT type=text id=namefld name=namefld onChange="ValidateData()"> <BR>
<INPUT type=submit>
</FORM>
</BODY>
</HTML>
Documentation about the HTML and DHTML features discussed in this article can be found at the MSDN Web Workshop.
Also, see the following article in the Microsoft Knowledge Base for related information about submitting data in a form:
Q172064 HOWTO: Submitting Data from an ActiveX Control in a Form
Additional query words:
Keywords : kbIE300 kbIE301 kbIE401 kbScript kbIE302 kbIE401sp1 kbIE401sp2 kbGrpInet kbIE500
Version : WINDOWS:3.0,3.01,3.02,4.0,4.01,4.01 SP1,4.01 SP2,5.0,5.0dp1,5_beta
Platform : WINDOWS
Issue type : kbinfo
Last Reviewed: May 25, 1999