Helpful Information
 
 
Category: JavaScript Development
Form Validation w/ Javascript & PHP

I have a strange problem when trying to validate a PHP generated form using JS to perform the validation.

I have the statement:

<form method='post' action='https://forums.devshed.com/archive/index.php/$PHP_SELF' onSubmit='return validateForm(this);'>

as my Form statement. I have no problem processing the form and posting to my MySQL db, but the validation will not occur.

Just for fun I removed the action statement, so that the statement was:

<form method='post' onSubmit='return validateForm(this);'>

and oddly, PHP still processed the form and wrote to my database. This seems strange that the form is still being processed, despite not having an action statement.

Any ideas about why this would happen? Suggestions as to the best method to validate a form client side before processing by PHP?

thanks,

michael

Hi,

Your idea is correct as you state "onSubmit()" (the form is processed on submission), but when you put an action and onsubmit together, then the action attribute overrules the onSubmit() function.

So why don't you leave it: <form method='post' onSubmit='return validateForm(this);'>, as it does exactly what you want it to do? It is a correct way!

Bon chance,

Peter

But, after validating the form, I wish to process the form via PHP.

Is there a way via JS to "POST" the form after validation?

thanks,

michael

Yes there is.
The way I normally do it is by using a normal button to trigger the JS and then submit the form by JS, like:

<HTML>
<HEAD>
...
<SCRIPT TYPE="text/javascript">
function validate(form) {
OK=false;
// do the things you want to validate
... (set OK to false or true according to validation)
// submit form when OK
if(OK) {
form.submit();
}
else {
//do something else
alert("You did it wrong!");
}
</SCRIPT>
...
<HEAD>
<BODY>
<FORM NAME="myform" ACTION="myfile.php3" METHOD="POST">
...
<INPUT TYPE="SUBMIT" VALUE="Submit" onClick="validate(this.form);">
</FORM>
</BODY>
</HTML>

Peter

That s very useful to me.

thanks

Johnny...










privacy (GDPR)