3. Validation of data with ArrayerValidate - adwins/Arrayer GitHub Wiki
3. Validation of data with ArrayerValidate.
Validation of data with ArrayerValidate.
/** * Arrayer has an auxiliary class ArrayerValidate to validate data. * * To use it you have Arrayer::validate() method that provides a tunnel to ArrayerValidate. */ $post = new Arrayer; $post->check('password'); $post->password->validate()->is_empty()->on_true('Empty password'); /** * Now we have added an error with error text "Empty password" to $post. * We can do some other validations on different variables and then get all errors * as an array, each key is a field name, each value is an error text. */ $errors = $post->get_errors(); /** * For example, * $errors = array( * 'password' => 'Empty password', * 'age' => 'Age is outbounding', * ); */ /** * You can construct validation queues: */ $post->password->validate() ->is_empty()->on_true('Empty password') ->md5()->unless($password_etalon, 'Incorrect password'); /** * If a value is empty, we log an error, any other validations won't be applied. */ /** * How to construct validation: * Arrayer::validate() returns an ArrayerValidate object expecting an Arrayer method * as next chain. The result of that method is hooked up to ArrayerValidate object * expecting conditions: `on_true`, `on_false`, `on` or `unless`. * After conditions you can add a new validation task to the queue. * * Conditions: * * ArrayerValidate::on_true(string $error_text) * Error raises when the result of previous method is boolean true. * * ArrayerValidate::on_false(string $error_text) * Error raises when the result of previous method is boolean false. * * ArrayerValidate::on(mixed $expected_value, string $error_text) * Error raises when the result of previous method is equal to expected_value. * * ArrayerValidate::unless(mixed $expected_value, string $error_text) * Error raises when the result of previous method is not equal to expected_value. * */ /** * You can validate several variables ot once: */ $post->validate() ->on_empty('username', 'Name is empty!') ->on_empty('age', 'Age is empty!') ->on_empty('country', 'Country is empty!'); /** * It is like shortcut to $post->var->validate()->is_empty()->on_true('var is empty'); */ /** * After these quick validations you can proceed next validations if everything is ok */ if ($post->validate()->is_ok()){ $post->age->validate()->in_range(10, 90)->on_false('Age is outbounding'); // etc. }