You are currently browsing Crystal’s documentation for the 0.4 version - Switch to version: 0.3

Data validation

Data validation is an important part of any application, as it helps to make sure that the data conforms to the business rules of the application.Crystal provides a comprehensive data validation class that helps minimize the amount of code you'll write.

Validation process

In Crystal the data validation process is simple. You supply array with data - for example post array, then you define the validation rules and if Crystal finds any errors in returns an array with errors. You can apply one rule per field or multiple rules per field. For example you can check the email field for valid email and the title field for presence, minimum characters and maximum characters.

Syntax

In Crystal 0.4 the validation class has a new simplified syntax. Multiple rules are separated with |, options with comma and array of values with space

// Multiple rules per field separated with |
'title' => array('required | alpha_numeric')

// Field options
'title' => array('required, message: This field is required')

// Array of values
'file_extension' => array('extension:(jpg png gif psd ai)')

Quick example


$data = array
(
'title' => 'my title',
'password' => 'test',
'email' => 'john_doe@yahoo.com'
);

$rules = array
(
'title' => array('required, message: Enter value'),
'password' => array('required'),
'email' => array('valid_email | required')
)

$validation = Crystal::validation($rules, $data);


if($validation->passed == TRUE)
{
    echo "No errors";
}
else
{
    print_r($validation->errors);
}