I have looked for better ways to handle validation for as long as I’ve been developing web applications. Catching multiple validation errors is frequently necessary, so I wanted to know if there was a better way to do it than the following.
Right now I have an assert method in a framework I’ve developed myself. An example of the method is this:
assert(($foo == 1), 'Foo is not equal to 1');
If the condition in the first argument is false, the error message in the second argument is added to an $errors array (which is wrapped in a class (referenced by $eh below) that provides convenience functions such as hasErrors()).
This method works but is messy in practice. Consider this code:
public function submit($foo, $bar, $baz)
{
assert(($foo == 1), 'Foo is not equal to 1');
assert(($bar == 2), 'Bar is not equal to 2');
if (!$eh->hasErrors())
{
assert(($baz == 3), 'Baz is not equal to 3');
if (!$eh->hasErrors())
{
finallyDoSomething();
return;
}
}
outputErrors();
}
This is something fairly common. I want to check two conditions before moving on, and then if those pass, check a third condition before finally doing what I want to do. As you can see, most of the lines in this code are related to validation. In a real application, there will be more validation and possibly more nested if statements.
Does anyone have a better structure for handling validation than this? If there are frameworks that handle this more elegantly, what are they and how do they accomplish it? Multiple nested if statements seem like such a ‘brute-force’ solution to the problem.
Just a note, I understand it would probably be a good idea to wrap some common validation functions in a class so that I can check length, string format, etc., by calling those functions. What I am asking is a cleaner approach to the code structure, not how I am actually checking the errors.
Thank you!
Please check Respect\Validation. It’s a library built for that purpouse. It can handle multiple rules very easily and uses exceptions for errors. Here is a quick sample:
Now using exceptions:
In the sample above, the
$errorsvariable would be something like this:I broke two previously declared rules using “foo # bar”: It has whitespace and it has a non-alnum char. For every rule that doesn’t pass, a message will be returned. Since “length” is OK, the error message is null.
The documentation includes several more samples including nested, hierarchical rules and better exception handling. Also has a extensive list of samples for all of the 30+ built in validators.
Hope that helps!