Forum Moderators: open

Message Too Old, No Replies

Stop the browser during form validation?

         

ahmedtheking

7:50 pm on Aug 26, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Is it possible to stop the browser while JS validates a form?

rocknbil

3:34 am on Aug 27, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Are you saying that it validates but submits anyway?

<form method="post" action="yourscript.cgi" onSubmit="return false;">
<input type="submit" onClick="yourValidationRoutine(this.form);" value="Submit">
</form>
<script type="text/javascript">
function yourValidationRoutine(form) {
if (some_error) {alert(some_error); }
else { form.submit(); }
}
</script>

Here is what is happening: if Javascript is enabled, return false on submit will prevent the form from submitting via the submit button. For this reason, if it passes validation in yourValidationRoutine you must execute form.submit(); to submit the form.

If, however, Javascript is DISABLED, which is getting more and more common as users become wise to it's abuse, all Javascript commands will be ignored and the form will submit anyway. Many try to circumnavigate this by using the input type=button, but without Javascript those will do nothing. Then you have no orders or no contacts, and to the end user, your site is broken.

So you MUST use an input type=submit, and whatever Javascript screening you do in the browser you must replicate on the server side.

RonPK

8:46 am on Aug 27, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Many forms can be submitted by hitting the return/enter key on the keyboard. In such cases a onclick-handler in a submit button will not be triggered. So it's preferable to trigger the validation with the onsubmit handler, and have the validation return true or false. If true, carry on and submit the form; if false, stop.

<form onsubmit="return checkform(this)" action=[..]> 
<input type="text" name="myname">
<input type="submit" value="go!">
</form>

<script type="text/javascript">
funtion checkform(f) {
if (f.myname.value == '') {
alert('hey!');
return false;
} else {
return true;
}
}
</script>

[edited by: RonPK at 8:47 am (utc) on Aug. 27, 2006]

ahmedtheking

9:47 am on Aug 30, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ok, so in the 'validateform()' func, shall I start with 'form.onsubmit = return false', validate and then 'form.submit();'

The form is also validated via PHP but it'll be nicer to have it done with effects via JS. But people with JS off can still use it.