How do I prevent a form from being submitted, until all required fields are correct ?

Submitted on: 1/5/2015 11:42:00 AM
By: iNet1 (from psc cd)  
Level: Intermediate
User Rating: By 5 Users
Compatibility: VbScript (browser/client side)
Views: 822
     How do I prevent a form from being submitted, until all required fields are correct ? Only one field is used in the example. Every time the user clicks the OK button, the onClick event fires. If it passes the test the form will submit, else the focus will be placed on the textbox, an alert will appear and the submit button will be disabled, which stops the submit process. The onMouseMove event is used to enable the button again. I just added the error handling code in case an error comes up. It is actually not necessary, you can just enable the button again. I use the onControlSelect event on the submit button, because sometimes after being disabled, the button looks like it is embedded in the page. The above event fixes it. The above can be applied to multiple textboxes, and multiple conditions and arguments can be used. It saves time and space as the validation is done on the current page, before the form is submitted. Otherwise the user has to go through the laborious task of clicking the back button on the posting page to be redirected to the previous page, and fix a simple mistake. I've had comments that the JavaScript return false statement is a better solution. Unfortunately the return false; statement doesn't seem to work when you are using frames. I hope you find this usefull !.

&lt;SCRIPT language="VBScript">
sub cmdOK_onClick
 If Len(document.form1.txtEmpNo.value) > 8 Then
	alert"You have entered an invalid Employee number !"
	document.form1.cmdOK.disabled = True
end sub
sub Enable
 On Error Resume Next
 document.form1.cmdOK.disabled = False
end sub
<body onMouseMove="Enable">
<form name="form1" method="POST" action="test.htm">
<input type="text" name="txtEmpNo">
<input type="submit" name="cmdOK" value="OK" onControlSelect="cmdOK_onClick">

Other 1 submission(s) by this author


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

Other User Comments

 There are no comments on this submission.

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)

To post feedback, first please login.