Forum Moderators: coopster
I have a html page with the form, calling my php page that connects to database and submits the data from form into my database.
Now that I have that working, I want to check for required fields and warn the user what fields need to be filled out without having them hit back and redoing the form from scratch.
Thanx.
The way I do this is with Javascript:
<script>
function validateForm(frm) {
if(frm.name.value.length ==0 ) {
alert("Please enter a Name!");
return false;
}
else {return true; }
}
</script>
<form ... onSubmit="return validateForm(this);">
Of course, Javascript can be disabled, so always validate the information on next page as well using PHP, but this will notify most people if they forget a required field, etc. You can do multiple checks to: make sure an email address is entered, make sure it's in the correct format, make sure a "new_name" has a value if they choose "New" from a drop-down, etc.
Chad
for(var i = 0; i < f.length; i++) {
var e = f.elements[i];
if (((e.type == "text") ¦¦ (e.type == "textarea")) &&!e.optional) {
// first check if the field is empty
if ((e.value == null) ¦¦ (e.value == "") ¦¦ isblank(e.value)) {
empty_fields += "\\n " + e.name;
continue;
}
Always validate through php too though. The javascript just saves on server time/bandwidth.
JavaSCRIPT (don't start interchanging the name of the scripting language Javascript with the programming language Java, mgworek ... you're a programmer, now!) + PHP provides the speed and client-side responsibility of the scripting language with the protection and reliability of the server-side language. Using Javascript for validation with those clients that accept it reduces your server load, too, as mealybar noted.
Check at the client but verify at the server. And when the data comes in, verify again and munge at the server.
Never trust client data, even if you think it's been verified.