Validation


Description


The validation class provides a simple and consistent way of validating user input.


Methods


__construct(array $input)


Create a validation object by passing an array to the constructor.


$validate = new Validate($_POST);

factory(array $input)


The factory methods returns a validation object and allows you to chain methods.


$valid = Validation::factory($_POST)
         ->rule('username', 'required', 'The username field is required')
         ->rule('password', 'required', 'The password field is required')
         ->process($errors);

rule(string $field, mixed $function, string $error)


The rule method adds a validation rule to the queue. You an use any callback function to validate input as long as it returns a boolean value.


// Checks that the all fields are filled out

$validate->rule('*', 'required', 'All fields are required');

// Checks that the username is no longer than 25 characters

$validate->rule('username', array('maxLength', array(25)), 'Your username cannot be longer than 25 characters');

// Checks that the year is numeric using PHP's internal is_numaric function

$validate->rule('year', 'is_numeric', 'The year must be a numeric value');

// Checks that the user is between 18 and 150 years old

$validate->rule('age', function($age)
{
	return is_numeric($age) && $age >= 18 && $age <= 150;
}, 'You must be between 18 and 150 to complete this survey');

Here's a list of predefined validation rules that you can use:


Name Description
required Checks that the field is not empty.
minLength Checks that the input is at least n characters long.
maxLength Checks that the input is less than n + 1 characters long.
exactLength Checks that the input is exactly n characters long.
match Checks that the input is matches another field.
regex Checks that the input matches a custom regex pattern.
email Checks that the input is a valid email address.
emailDomain Checks that the domain of an email address has a valid MX reccord.
ip Checks that input is a valid IP address.
url Checks that input is a valid URL.

process([array &$errors = null])


Processing validation rules is done by using the process method. It will return TRUE if all fields validated and FALSE if some of the rules failed.


$valid = Validation::factory($_POST)
         ->rule('username', 'required', 'The username field is required')
         ->rule('password', 'required', 'The password field is required')
         ->process($errors);

if($valid)
{
	echo 'everything is ok!';
}
else
{
	echo HTML::ul($errors);
}