There are a lot of ways to do this. How I do it is I have two validation objects, one is static and called Validate, the other is concrete and called Validator. Validate is just a whole bunch of validation methods and I keep adding to it. I keep it separate because sometimes I want to validate something quickly in code so I just call a static method.
My stuff is setup so that I have one validator for each input field, and each field is its own class, here is how I would set it up if it was outside a class.
// This is all in php5 and the class uses __get and __set
$val = new Validator() ;
$val
->required
->max_length(15)
->min_length(5)
->alphanumeric
->errorMsg( 'Your password sucks' ) ;
if( !$val->test( $_POST['password'] ) )
{
echo $val->getError() ;
}
// Do a quick test using the static class that holds the tests
if( !validate::alphanumeric( $_POST['password ) ).....
I use a field collection but if you aren't using objects for form generation then you can create some sort of validation collection and add rules to it, maybe like
$val = new ValidationThingy() ;
// Add a rule for a value in the array named 'password'
$val->addRule('password')
->required
->max_length(15)
->min_length(5)
->alphanumeric
->errorMsg( 'Your password sucks' ) ;
// Set the array to test
$val->setVars( $_POST ) ;
// Tell the object to loop through every rule and test matching objects
// from $_POST
if( !$val->validate() )
{
print_r($val->getErrors()) ;
}
Again, there are a lot of ways to do this, the right way depends on your style and how your existing classes are setup, so you don't have to do it this way (which some others think is nuts).
Edit: You can view the source for all of this by viewing the source of database abstraction layer at lawngnome.tigris.org (just check the source out of SVN). FYI the documentation that is on the homepage is out of date and I have only commented about half of lawngnome, but the validation part of it is rock solid.