Handling Required Form Fields

I’m trying to discover the best way to handle the validation of required fields in forms. I want to create a method which can be re used in all my future apps.

This is what I have right now but its not quite working yet.

//$required[0] is field name $required[1] is text used for error message
$required = array(
     array("fname","First Name"),
     array("lname","Last Name"),
     array("email","Email Address"),
     array("pass2","Password Confirm")

foreach($required as $var){
     //$data is $_POST passed into the function
          $this->errors[] = $var[1]." Required";

Aside from finding the problems in my current method. Do you have a standardized way of handling form validation with required fields?

Well a validation class could help. Then you could do stuff like…

$required = array( 
     array('fname' => 'string'), 

foreach ($required as $require => $type)
    if (!isset($data[$require]) || !Validator::test($data[$require], $type))
        $this->errors[] = $require;

Then when showing errors decided what to show depending on the string that is stored in errors. For example SMF does things like $txt[‘errors_fname_required’].

This isn’t how I would go about doing it, I would most likely go through each $_POST manually to make sure everything is nice and valid instead of a loop. It isn’t that much more code to just go through them all instead of looping, your form shouldn’t be big enough to require saving time with a loop.

Perhaps this PHP Form Validation Script will be useful for you

If you are planning on reusing it in future apps then I agree a validation class is the way to go. There are a few on the PHPClasses website, may be browse through those, or just code your own. The benefits of this would be that you could set your own validation rules and also set it in a way that all data is prepped and ready to be inserted into your respective DB.

Error handling also becomes much more organized. For example my form validation class I built some time ago, is still going strong. I have set the errors in an array and now I know them extremely well and I can just set them on the fly.