Is it possible to validate a form with PHP and JavaScript? I\'m currently able to do both using my existing form
, but only on
I've not tried this, but off the top of my head; you don't need the language="JavaScript"
in your form for it to use the onsumbit
event handler. If that event evaluates to true
, then the form will be submitted as normal (so PHP will see it and can do its validation).
It's good to see you're not relying on client-side validation. It's trivial to disable JavaScript in a browser. One should always validate one's input.
UPDATED in responce to comments
First of all, javascript can't be a secure validator, for obvious reasons! it can be a fancy way of displaying alerts and notice but is just sugar!
Real validation must be done in PHP or other server-side language as well as on Database side by checking and formatting values!
This simple script is just a demostration of how you can built a smart validator, but of course is just a proof of concept!
DEMO: http://jsbin.com/aceze/29
$(function() {
$('#myform').submit(function() {
var error = false; // flag
$('.email,.digits,.empty,.some').each(function() {
var check = this.className;
if (check == 'empty') if (!checkEmpty(this.value)) error = true;
if (check == 'digits') if (!checkDigits(this.value)) error = true;
if (check == 'email') if (!checkEmail(this.value)) error = true;
if (check == 'some') if (!checkSome(this.value)) error = true;
if (error) {
$(this).css('border', '1px solid red');
} else {
$(this).css('border', '1px solid green');
}
});
if (error) {
return false;
}
});
});
Then regarding the <form>
action, you don't need to have the path of the php page in it, but you must use AJAX for make the POST OR just leave the review.php
where is see theese snippets below:
// FIRST SNIPPET action="#"
if ( error == false ) {
//if all is ok give our form it's php
$(this).attr('action','review.php');
} else {
// error
// place false here so the form don't submit if validation fail!
return false;
}
// SECOND SNIPPET action="review.php"
if ( error == true ) {
// form submit only if validation pass
return false;
}
// THIRD SNIPPET action="#" AJAX
if ( error == false ) {
// success
} else {
// error
}
// this false prevent the form submit in anycase, cause we use AJAX
return false;
I don´t really see what the problem is, if your onsubmit
action returns false
in case of a non (javascript) validated form, the form simply doesn´t get submitted if javascript is enabled.
As soon as the form gets submitted, the php can do whatever it wants, validate, return errors, etc.
Don't rely too much on JS for this kind of stuff. Yes, you can validate to prevent users errors, but someone could easily create a .html
and do
<form action="http://yoursite.com/review.php" method="post">
<input type="submit">
</form>
And bypass any JS validation you have. Validate in PHP as you would if you hadn't any JS validation.