Forum Moderators: coopster

Message Too Old, No Replies

best way to error check/validate required fields, php or java?

         

mgworek

7:07 pm on Mar 9, 2006 (gmt 0)

10+ Year Member



Just wondering what everyones thoughts were.

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.

ChadSEO

7:51 pm on Mar 9, 2006 (gmt 0)

10+ Year Member



mgworek,

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

phparion

8:23 pm on Mar 9, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



PHP PHP PHP PHP PHP and PHP

whoisgregg

9:03 pm on Mar 9, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Do both. Validate using javascript as a usability aid to your visitors, but only trust the PHP validation.

mealybar

1:27 am on Mar 10, 2006 (gmt 0)

10+ Year Member



If you add some javascript testing all input text and text area elements defined in a page.

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.

StupidScript

3:01 am on Mar 10, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Agreeing with everyone ...

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.