1
Beginners - Learning PHP / Re: Validate Function Not working
« on: February 20, 2012, 01:34:40 PM »
A couple of things...I'm not going to preach on this too much, but to be honest it's a really bad practice to rely entirely upon Javascript to handle form validation. All a user needs to do then to get around your validation scheme is turn off Javascript in their browser. So...add some validation on the server side in addition to what you've got going on in the JS.
As to your JS...I might be missing something critical here, but I think your problem lies in the fact that you're returning out of your validate_form function as soon as you check the first field. You only call validate_form the one time, (on form submit), and once you return out of a function, that function is done...it won't keep going. So, what's happening is your first field is validating, and none of the other fields are being checked assuming that one is good. You can confirm my theory by putting an invalid value in the Name field and seeing if it gives you your error.
Assuming I'm correct, the solution is to get rid of all those returns and return just one time after all the fields have been checked. You can do that by setting up a variable that stores the state of the form depending upon whether or not all the fields are valid:
Sorry about the crap indentation, but you get the idea...
Hope this helps!!
As to your JS...I might be missing something critical here, but I think your problem lies in the fact that you're returning out of your validate_form function as soon as you check the first field. You only call validate_form the one time, (on form submit), and once you return out of a function, that function is done...it won't keep going. So, what's happening is your first field is validating, and none of the other fields are being checked assuming that one is good. You can confirm my theory by putting an invalid value in the Name field and seeing if it gives you your error.
Assuming I'm correct, the solution is to get rid of all those returns and return just one time after all the fields have been checked. You can do that by setting up a variable that stores the state of the form depending upon whether or not all the fields are valid:
Code: [Select]
<script>
function validate_form(){
var form_dirty = false
if(firstName == "" || firstName == null){
form_dirty = true;
}
if(lastName == "" || lastName == null){
form_dirty = true;
}
if(form_dirty){
alert("There are problems with your form submission");
return false;
}
return true:
}
</script>
Sorry about the crap indentation, but you get the idea...
Hope this helps!!
