respect-validation/docs
2016-11-05 14:14:39 +01:00
..
Age.md Documentation improvements 2015-10-19 22:55:05 -02:00
AllOf.md Documentation improvements 2015-10-19 22:55:05 -02:00
Alnum.md Documentation improvements 2015-10-19 22:55:05 -02:00
Alpha.md Make all rules mandatory 2015-10-07 01:00:39 -03:00
AlwaysInvalid.md Documentation improvements 2015-10-19 22:55:05 -02:00
AlwaysValid.md Documentation improvements 2015-10-19 22:55:05 -02:00
ArrayType.md Rename "Iterable" to "IterableType" 2016-08-03 10:43:33 +02:00
ArrayVal.md Rename "Iterable" to "IterableType" 2016-08-03 10:43:33 +02:00
Attribute.md Documentation improvements 2015-10-19 22:55:05 -02:00
Bank.md Update version constraints on composer.json file 2016-11-05 14:14:38 +01:00
BankAccount.md Update version constraints on composer.json file 2016-11-05 14:14:38 +01:00
Between.md Documentation improvements 2015-10-19 22:55:05 -02:00
Bic.md Update version constraints on composer.json file 2016-11-05 14:14:38 +01:00
BoolType.md Documentation improvements 2015-10-19 22:55:05 -02:00
BoolVal.md Fix typo on the title 2015-11-13 13:18:29 -02:00
Bsn.md Create "Nif" rule 2016-10-09 17:50:52 +02:00
Call.md Use short array syntax 2015-10-17 22:56:32 -03:00
CallableType.md Documentation improvements 2015-10-19 22:55:05 -02:00
Callback.md Documentation improvements 2015-10-19 22:55:05 -02:00
Charset.md Documentation improvements 2015-10-19 22:55:05 -02:00
Cnh.md Create "Nif" rule 2016-10-09 17:50:52 +02:00
Cnpj.md Create "Nif" rule 2016-10-09 17:50:52 +02:00
Cntrl.md Documentation improvements 2015-10-19 22:55:05 -02:00
CONCRETE_API.md Documentation improvements 2015-10-19 22:55:05 -02:00
Consonant.md Documentation improvements 2015-10-19 22:55:05 -02:00
Contains.md Documentation improvements 2015-10-19 22:55:05 -02:00
Countable.md Rename "Iterable" to "IterableType" 2016-08-03 10:43:33 +02:00
CountryCode.md Documentation improvements 2015-10-19 22:55:05 -02:00
Cpf.md Documentation improvements 2015-10-19 22:55:05 -02:00
CreditCard.md Allow the define brands for credit card validation 2016-04-06 16:42:49 -03:00
CurrencyCode.md Documentation improvements 2015-10-19 22:55:05 -02:00
Date.md Documentation improvements 2015-10-19 22:55:05 -02:00
Digit.md Make all rules mandatory 2015-10-07 01:00:39 -03:00
Directory.md Documentation improvements 2015-10-19 22:55:05 -02:00
Domain.md Documentation improvements 2015-10-19 22:55:05 -02:00
Each.md Fix missing change from arr() to arrayVal() 2016-04-06 10:08:40 +02:00
Email.md Documentation improvements 2015-10-19 22:55:05 -02:00
EndsWith.md Documentation improvements 2015-10-19 22:55:05 -02:00
Equals.md Documentation improvements 2015-10-19 22:55:05 -02:00
Even.md Documentation improvements 2015-10-19 22:55:05 -02:00
Executable.md Documentation improvements 2015-10-19 22:55:05 -02:00
Exists.md Documentation improvements 2015-10-19 22:55:05 -02:00
Extension.md Documentation improvements 2015-10-19 22:55:05 -02:00
Factor.md Documentation improvements 2015-10-19 22:55:05 -02:00
FalseVal.md Documentation improvements 2015-10-19 22:55:05 -02:00
Fibonacci.md Create "Fibonacci" rule 2016-02-13 14:02:21 -02:00
File.md Documentation improvements 2015-10-19 22:55:05 -02:00
FilterVar.md Merge branch '0.9' into 1.0 2016-05-05 13:14:24 +02:00
Finite.md Documentation improvements 2015-10-19 22:55:05 -02:00
FloatType.md Documentation improvements 2015-10-19 22:55:05 -02:00
FloatVal.md Documentation improvements 2015-10-19 22:55:05 -02:00
Graph.md Documentation improvements 2015-10-19 22:55:05 -02:00
HexRgbColor.md Documentation improvements 2015-10-19 22:55:05 -02:00
Identical.md Documentation improvements 2015-10-19 22:55:05 -02:00
IdentityCard.md Create "Vatin" rule (VAT identification number) 2016-09-19 09:50:50 +02:00
Image.md Create "Image" rule 2015-12-14 10:14:26 -02:00
Imei.md Create "Imei" rule 2015-10-23 07:53:59 -02:00
In.md Documentation improvements 2015-10-19 22:55:05 -02:00
Infinite.md Documentation improvements 2015-10-19 22:55:05 -02:00
INSTALL.md On documentation, bump supported version to 5.4 2015-10-17 14:56:26 -03:00
Instance.md Documentation improvements 2015-10-19 22:55:05 -02:00
IntType.md Documentation improvements 2015-10-19 22:55:05 -02:00
IntVal.md Documentation improvements 2015-10-19 22:55:05 -02:00
Ip.md Documentation improvements 2015-10-19 22:55:05 -02:00
IterableType.md Rename "Iterable" to "IterableType" 2016-08-03 10:43:33 +02:00
Json.md Documentation improvements 2015-10-19 22:55:05 -02:00
Key.md Documentation improvements 2015-10-19 22:55:05 -02:00
KeyNested.md Use short array syntax 2015-10-17 22:56:32 -03:00
KeySet.md Documentation improvements 2015-10-19 22:55:05 -02:00
KeyValue.md Create "KeyValue" rule 2015-10-13 07:37:12 -03:00
LanguageCode.md Create "LanguageCode" rule 2015-10-26 23:12:21 -03:00
LeapDate.md Documentation improvements 2015-10-19 22:55:05 -02:00
LeapYear.md Documentation improvements 2015-10-19 22:55:05 -02:00
Length.md Documentation improvements 2015-10-19 22:55:05 -02:00
Lowercase.md Documentation improvements 2015-10-19 22:55:05 -02:00
MacAddress.md Documentation improvements 2015-10-19 22:55:05 -02:00
Max.md Documentation improvements 2015-10-19 22:55:05 -02:00
Mimetype.md Documentation improvements 2015-10-19 22:55:05 -02:00
Min.md Documentation improvements 2015-10-19 22:55:05 -02:00
MinimumAge.md Documentation improvements 2015-10-19 22:55:05 -02:00
Multiple.md Documentation improvements 2015-10-19 22:55:05 -02:00
Negative.md Documentation improvements 2015-10-19 22:55:05 -02:00
NfeAccessKey.md Documentation improvements 2015-10-19 22:55:05 -02:00
Nif.md Create "Nif" rule 2016-10-09 17:50:52 +02:00
No.md Documentation improvements 2015-10-19 22:55:05 -02:00
NoneOf.md Documentation improvements 2015-10-19 22:55:05 -02:00
Not.md Documentation improvements 2015-10-19 22:55:05 -02:00
NotBlank.md Use short array syntax 2015-10-17 22:56:32 -03:00
NotEmpty.md Documentation improvements 2015-10-19 22:55:05 -02:00
NotOptional.md Documentation improvements 2015-10-19 22:55:05 -02:00
NoWhitespace.md Documentation improvements 2015-10-19 22:55:05 -02:00
NullType.md Documentation improvements 2015-10-19 22:55:05 -02:00
Numeric.md Documentation improvements 2015-10-19 22:55:05 -02:00
ObjectType.md Documentation improvements 2015-10-19 22:55:05 -02:00
Odd.md Documentation improvements 2015-10-19 22:55:05 -02:00
OneOf.md Documentation improvements 2015-10-19 22:55:05 -02:00
Optional.md Remove user-defined optional values 2015-10-15 11:14:20 -03:00
PerfectSquare.md Documentation improvements 2015-10-19 22:55:05 -02:00
Pesel.md Create "Vatin" rule (VAT identification number) 2016-09-19 09:50:50 +02:00
Phone.md Documentation improvements 2015-10-19 22:55:05 -02:00
PhpLabel.md Create "PhpLabel" rule 2016-03-04 21:48:25 -03:00
Positive.md Documentation improvements 2015-10-19 22:55:05 -02:00
PostalCode.md Better examples for PostalCode rule 2015-11-25 18:03:11 -02:00
PrimeNumber.md Documentation improvements 2015-10-19 22:55:05 -02:00
Prnt.md Documentation improvements 2015-10-19 22:55:05 -02:00
Punct.md Documentation improvements 2015-10-19 22:55:05 -02:00
Readable.md Documentation improvements 2015-10-19 22:55:05 -02:00
README.md Updated the documentation on creating Custom rules in docs/README.md. The information now correctly reflects how you go about creating your own custom rule. 2016-08-26 14:15:21 -05:00
Regex.md Documentation improvements 2015-10-19 22:55:05 -02:00
ResourceType.md Documentation improvements 2015-10-19 22:55:05 -02:00
Roman.md Documentation improvements 2015-10-19 22:55:05 -02:00
ScalarVal.md Documentation improvements 2015-10-19 22:55:05 -02:00
Sf.md Upgrade "symfony/validator" version 2016-11-05 14:14:39 +01:00
Size.md Documentation improvements 2015-10-19 22:55:05 -02:00
Slug.md Documentation improvements 2015-10-19 22:55:05 -02:00
Space.md Documentation improvements 2015-10-19 22:55:05 -02:00
StartsWith.md Documentation improvements 2015-10-19 22:55:05 -02:00
StringType.md Documentation improvements 2015-10-19 22:55:05 -02:00
SubdivisionCode.md Documentation improvements 2015-10-19 22:55:05 -02:00
SymbolicLink.md Documentation improvements 2015-10-19 22:55:05 -02:00
Tld.md Documentation improvements 2015-10-19 22:55:05 -02:00
TrueVal.md Documentation improvements 2015-10-19 22:55:05 -02:00
Type.md Documentation improvements 2015-10-19 22:55:05 -02:00
Uploaded.md Documentation improvements 2015-10-19 22:55:05 -02:00
Uppercase.md Documentation improvements 2015-10-19 22:55:05 -02:00
Url.md Documentation improvements 2015-10-19 22:55:05 -02:00
VALIDATORS.md Create "Nif" rule 2016-10-09 17:50:52 +02:00
Vatin.md Create "Vatin" rule (VAT identification number) 2016-09-19 09:50:50 +02:00
Version.md Documentation improvements 2015-10-19 22:55:05 -02:00
VideoUrl.md Create "VideoUrl" rule 2015-09-15 23:41:24 -03:00
Vowel.md Documentation improvements 2015-10-19 22:55:05 -02:00
When.md Rename rule "Int" to "IntVal" 2015-10-07 11:46:57 -03:00
Writable.md Documentation improvements 2015-10-19 22:55:05 -02:00
Xdigit.md Documentation improvements 2015-10-19 22:55:05 -02:00
Yes.md Documentation improvements 2015-10-19 22:55:05 -02:00
Zend.md Update version constraints on composer.json file 2016-11-05 14:14:38 +01:00

Feature Guide

Namespace import

Respect\Validation is namespaced, but you can make your life easier by importing a single class into your context:

use Respect\Validation\Validator as v;

Simple validation

The Hello World validator is something like this:

$number = 123;
v::numeric()->validate($number); // true

Chained validation

It is possible to use validators in a chain. Sample below validates a string containing numbers and letters, no whitespace and length between 1 and 15.

$usernameValidator = v::alnum()->noWhitespace()->length(1, 15);
$usernameValidator->validate('alganet'); // true

Validating object attributes

Given this simple object:

$user = new stdClass;
$user->name = 'Alexandre';
$user->birthdate = '1987-07-01';

Is possible to validate its attributes in a single chain:

$userValidator = v::attribute('name', v::stringType()->length(1,32))
                  ->attribute('birthdate', v::date()->age(18));

$userValidator->validate($user); // true

Validating array keys is also possible using v::key()

Note that we used v::stringType() and v::date() in the beginning of the validator. Although is not mandatory, it is a good practice to use the type of the validated object as the first node in the chain.

Input optional

On oldest versions of Respect\Validation all validators treat input as optional and accept an empty string input as valid. Even though a useful feature that caused a lot of troubles for our team and neither was an obvious behavior. Also there was some people who likes to accept null as optional value, not only an empty string.

For that reason all rules are mandatory now but if you want to treat a value as optional you can use v::optional() rule:

v::alpha()->validate(''); // false input required
v::alpha()->validate(null); // false input required

v::optional(v::alpha())->validate(''); // true
v::optional(v::alpha())->validate(null); // true

By optional we consider null or an empty string ('').

See more on Optional.

Negating rules

You can use the v::not() to negate any rule:

v::not(v::intVal())->validate(10); // false, input must not be integer

Validator reuse

Once created, you can reuse your validator anywhere. Remember $usernameValidator?

$usernameValidator->validate('respect');            //true
$usernameValidator->validate('alexandre gaigalas'); // false
$usernameValidator->validate('#$%');                //false

Exception types

  • Respect\Validation\Exceptions\ExceptionInterface:
    • All exceptions implement this interface;
  • Respect\Validation\Exceptions\ValidationException:
    • Implements the Respect\Validation\Exceptions\ExceptionInterface interface
    • Thrown when the check() fails
    • All validation exceptions extend this class
    • Available methods:
      • getMainMessage();
      • setMode($mode);
      • setName($name);
      • setParam($name, $value);
      • setTemplate($template);
      • more...
  • Respect\Validation\Exceptions\NestedValidationException:
    • Extends the Respect\Validation\Exceptions\ValidationException class
    • Usually thrown when the assert() fails
    • Available methods:
      • findMessages();
      • getFullMessage();
      • getMessages();
      • more...

Informative exceptions

When something goes wrong, Validation can tell you exactly what's going on. For this, we use the assert() method instead of validate():

use Respect\Validation\Exceptions\NestedValidationException;

try {
    $usernameValidator->assert('really messed up screen#name');
} catch(NestedValidationException $exception) {
   echo $exception->getFullMessage();
}

The printed message is exactly this, as a nested Markdown list:

- All of the required rules must pass for "really messed up screen#name"
  - "really messed up screen#name" must contain only letters (a-z) and digits (0-9)
  - "really messed up screen#name" must not contain whitespace
  - "really messed up screen#name" must have a length between 1 and 15

Getting all messages as an array

The Markdown list is fine, but unusable on a HTML form or something more custom. For that you can use getMessages().

It will return all messages from the rules that did not pass the validation.

try {
    $usernameValidator->assert('really messed up screen#name');
} catch(NestedValidationException $exception) {
    print_r($exception->getMessages());
}

The code above may display something like:

Array
(
    [0] => "really messed up screen#name" must contain only letters (a-z) and digits (0-9)
    [1] => "really messed up screen#name" must not contain whitespace
    [2] => "really messed up screen#name" must have a length between 1 and 15
)

Getting messages as an array by name

If you want to get specific message by name you can use findMessages() passing the names of the rules you want:

try {
    $usernameValidator->assert('really messed up screen#name');
} catch(NestedValidationException $exception) {
    print_r($exception->findMessages(['alnum', 'noWhitespace']));
}

The findMessages() returns an array with messages from the requested validators, like this:

Array
(
    [alnum] => "really messed up screen#name" must contain only letters (a-z) and digits (0-9)
    [noWhitespace] => "really messed up screen#name" must not contain whitespace
)

Custom messages

Getting messages as an array is fine, but sometimes you need to customize them in order to present them to the user. This is possible using the findMessages() method as well:

$errors = $exception->findMessages([
    'alnum' => '{{name}} must contain only letters and digits',
    'length' => '{{name}} must not have more than 15 chars',
    'noWhitespace' => '{{name}} cannot contain spaces'
]);

For all messages, the {{name}} variable is available for templates. If you do not define a name it uses the input to replace this placeholder.

Message localization

You're also able to translate your message to another language with Validation. The only thing one must do is to define the param translator as a callable that will handle the translation:

$exception->setParam('translator', 'gettext');

The example above uses gettext() but you can use any other callable value, like [$translator, 'trans'] or you_custom_function().

After that, if you call getMainMessage() or getFullMessage() (for nested), the message will be translated.

Note that getMessage() will keep the original message.

Custom rules

You can also create and use your own rules. To do this, you will need to create a rule and an exception to go with the rule.

To create a rule, you need to create a class that extends the AbstractRule class and is within the Rules namespace. When the rule is called the logic inside the validate method will be executed. Here's how the class should look:

namespace My\Validation\Rules;

use Respect\Validation\Rules\AbstractRule;

class MyRule extends AbstractRule
{
    public function validate($input)
    {
        // Do something here with the $input and return a boolean value
    }
}

Each rule must have an Exception to go with it. Exceptions should be named with the name of the rule followed by the word Exception. The process of creating an Exception is similar to creating a rule but there are no methods in the Exception class. Instead, you create one static property that includes an array with the information below:

namespace My\Validation\Exceptions;

use \Respect\Validation\Exceptions\ValidationException;

class MyRuleException extends ValidationException
{
    public static $defaultTemplates = [
        self::MODE_DEFAULT => [
            self::STANDARD => 'Validation message if MyRule fails validation.',
        ],
        self::MODE_NEGATIVE => [
            self::STANDARD => 'Validation message if the negative of MyRule is called and fails validation.',
        ],
    ];
}

So in the end, the folder structure for your Rules and Exceptions should look something like the structure below. Note that the folders (and namespaces) are plural but the actual Rules and Exceptions are singular.

My
 +-- Validation
     +-- Exceptions
         +-- MyRuleException.php
     +-- Rules
         +-- MyRule.php

If you want Validation to execute your rule (or rules) in the chain, you must use v::with() passing your rule's namespace as an argument:

v::with('My\\Validation\\Rules\\');
v::myRule(); // Try to load "My\Validation\Rules\MyRule" if any

By default with() appends the given prefix, but you can change this behavior in order to overwrite default rules:

v::with('My\\Validation\\Rules', true);
v::alnum(); // Try to use "My\Validation\Rules\Alnum" if any

Validator name

On v::attribute() and v::key(), {{name}} is the attribute/key name. For others, is the same as the input. You can customize a validator name using:

v::date('Y-m-d')->between('1980-02-02', 'now')->setName('Member Since');

Zend/Symfony validators

It is also possible to reuse validators from other frameworks if they are installed:

$hostnameValidator = v::zend('Hostname')->assert('google.com');
$timeValidator     = v::sf('Time')->assert('22:00:01');

Validation methods

We've seen validate() that returns true or false and assert() that throws a complete validation report. There is also a check() method that returns an Exception only with the first error found:

use Respect\Validation\Exceptions\ValidationException;

try {
    $usernameValidator->check('really messed up screen#name');
} catch(ValidationException $exception) {
    echo $exception->getMainMessage();
}

Message:

"really messed up screen#name" must contain only letters (a-z) and digits (0-9)

See also: