respect-validation/docs
2015-10-18 18:50:07 -02:00
..
Age.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
AllOf.md Rename rule "Int" to "IntVal" 2015-10-07 11:46:57 -03:00
Alnum.md Fix typo on "Alnum" docs 2015-10-17 13:24:16 -03:00
Alpha.md Make all rules mandatory 2015-10-07 01:00:39 -03:00
AlwaysInvalid.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
AlwaysValid.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
ArrayType.md Create "ArrayType" rule 2015-10-18 18:01:11 -02:00
ArrayVal.md Refactor "ArrayVal" rule and add integration tests 2015-10-18 18:50:07 -02:00
Attribute.md Rename rule "String" to "StringType" 2015-10-07 11:52:03 -03:00
Bank.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
BankAccount.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Between.md Make all rules inclusive by default 2015-10-14 13:10:20 -03:00
Bic.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
BoolType.md Rename rule "Bool" to "BoolType" 2015-10-07 11:30:29 -03:00
Bsn.md Create "Bsn" rule 2015-10-16 22:19:33 +02:00
Call.md Use short array syntax 2015-10-17 22:56:32 -03:00
CallableType.md Use short array syntax 2015-10-17 22:56:32 -03:00
Callback.md Rename rule "Int" to "IntVal" 2015-10-07 11:46:57 -03:00
Charset.md Use short array syntax 2015-10-17 22:56:32 -03:00
Cnh.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Cnpj.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Cntrl.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
CONCRETE_API.md Add "CONCREATE_API.md" to repository 2015-02-12 15:07:10 -02:00
Consonant.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Contains.md Use short array syntax 2015-10-17 22:56:32 -03:00
Countable.md Create "Iterable" rule 2015-10-18 17:27:25 -02:00
CountryCode.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Cpf.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
CreditCard.md Update documentation 2015-02-12 14:37:33 -02:00
CurrencyCode.md Create "CurrencyCode" rule 2015-10-18 14:42:39 -02:00
Date.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Digit.md Make all rules mandatory 2015-10-07 01:00:39 -03:00
Directory.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Domain.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Each.md Use short array syntax 2015-10-17 22:56:32 -03:00
Email.md Update documentation 2015-02-12 14:37:33 -02:00
EndsWith.md Use short array syntax 2015-10-17 22:56:32 -03:00
Equals.md Remove identical checking from "Equals" rule 2015-10-13 13:29:31 -03:00
Even.md Rename rule "Int" to "IntVal" 2015-10-07 11:46:57 -03:00
Executable.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Exists.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Extension.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Factor.md Create "Factor" rule 2015-09-10 13:44:00 -03:00
FalseVal.md Rename rule "True" to "TrueVal" 2015-10-07 11:38:24 -03:00
File.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
FilterVar.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Finite.md Rename rule "Int" to "IntVal" 2015-10-07 11:46:57 -03:00
FloatType.md Create "FloatType" rule 2015-10-18 16:57:49 -02:00
FloatVal.md Create "FloatType" rule 2015-10-18 16:57:49 -02:00
Graph.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
HexRgbColor.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Identical.md Create "Identical" rule 2015-10-13 13:29:34 -03:00
In.md Use short array syntax 2015-10-17 22:56:32 -03:00
Infinite.md Rename rule "Int" to "IntVal" 2015-10-07 11:46:57 -03:00
INSTALL.md On documentation, bump supported version to 5.4 2015-10-17 14:56:26 -03:00
Instance.md Rename rule "Object" to "ObjectType" 2015-10-07 12:44:19 -03:00
IntType.md Create "IntType" rule 2015-10-16 23:43:01 -03:00
IntVal.md Rename rule "Int" to "IntVal" 2015-10-07 11:46:57 -03:00
Ip.md Update documentation 2015-02-12 14:37:33 -02:00
Iterable.md Create "Iterable" rule 2015-10-18 17:27:25 -02:00
Json.md Update documentation 2015-02-12 14:37:33 -02:00
Key.md Use short array syntax 2015-10-17 22:56:32 -03:00
KeyNested.md Use short array syntax 2015-10-17 22:56:32 -03:00
KeySet.md Use short array syntax 2015-10-17 22:56:32 -03:00
KeyValue.md Create "KeyValue" rule 2015-10-13 07:37:12 -03:00
LeapDate.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
LeapYear.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Length.md Use short array syntax 2015-10-17 22:56:32 -03:00
Lowercase.md Rename rule "String" to "StringType" 2015-10-07 11:52:03 -03:00
MacAddress.md Update documentation 2015-02-12 14:37:33 -02:00
Max.md Make all rules inclusive by default 2015-10-14 13:10:20 -03:00
Mimetype.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Min.md Make all rules inclusive by default 2015-10-14 13:10:20 -03:00
MinimumAge.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Multiple.md Rename rule "Int" to "IntVal" 2015-10-07 11:46:57 -03:00
Negative.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
NfeAccessKey.md Update documentation 2015-02-12 14:37:33 -02:00
No.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
NoneOf.md Rename rule "Int" to "IntVal" 2015-10-07 11:46:57 -03:00
Not.md Remove all rules shortcuts 2015-10-14 13:06:36 -03:00
NotBlank.md Use short array syntax 2015-10-17 22:56:32 -03:00
NotEmpty.md Use short array syntax 2015-10-17 22:56:32 -03:00
NotOptional.md Use short array syntax 2015-10-17 22:56:32 -03:00
NoWhitespace.md Make all rules mandatory 2015-10-07 01:00:39 -03:00
NullType.md Rename rule "NullValue" to "NullType" 2015-10-07 12:44:13 -03:00
Numeric.md Rename rule "Int" to "IntVal" 2015-10-07 11:46:57 -03:00
ObjectType.md Rename rule "Object" to "ObjectType" 2015-10-07 12:44:19 -03:00
Odd.md Rename rule "Int" to "IntVal" 2015-10-07 11:46:57 -03:00
OneOf.md Remove all rules shortcuts 2015-10-14 13:06:36 -03:00
Optional.md Remove user-defined optional values 2015-10-15 11:14:20 -03:00
PerfectSquare.md Update documentation 2015-02-12 14:37:33 -02:00
Phone.md Update documentation 2015-02-12 14:37:33 -02:00
Positive.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
PostalCode.md Add country code to postal code exception message 2015-09-24 00:49:25 -03:00
PrimeNumber.md Update documentation 2015-02-12 14:37:33 -02:00
Prnt.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Punct.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Readable.md Update documentation 2015-02-12 14:37:33 -02:00
README.md Use short array syntax 2015-10-17 22:56:32 -03:00
Regex.md Update documentation 2015-02-12 14:37:33 -02:00
ResourceType.md Rename rule "Resource" to "ResourceType" 2015-10-07 12:44:19 -03:00
Roman.md Make all rules mandatory 2015-10-07 01:00:39 -03:00
ScalarVal.md Use short array syntax 2015-10-17 22:56:32 -03:00
Sf.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Size.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Slug.md Update documentation 2015-02-12 14:37:33 -02:00
Space.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
StartsWith.md Use short array syntax 2015-10-17 22:56:32 -03:00
StringType.md Rename rule "String" to "StringType" 2015-10-07 11:52:03 -03:00
SubdivisionCode.md Create "SubdivisionCode" rule 2015-09-21 13:54:02 -03:00
SymbolicLink.md Update documentation 2015-02-12 14:37:33 -02:00
Tld.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
TrueVal.md Rename rule "True" to "TrueVal" 2015-10-07 11:38:24 -03:00
Type.md Rename rule "Scalar" to "ScalarVal" 2015-10-07 12:44:20 -03:00
Uploaded.md Update documentation 2015-02-12 14:37:33 -02:00
Uppercase.md Rename rule "String" to "StringType" 2015-10-07 11:52:03 -03:00
Url.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
VALIDATORS.md Create "ArrayType" rule 2015-10-18 18:01:11 -02:00
Version.md Update documentation 2015-02-12 14:37:33 -02:00
VideoUrl.md Create "VideoUrl" rule 2015-09-15 23:41:24 -03:00
Vowel.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
When.md Rename rule "Int" to "IntVal" 2015-10-07 11:46:57 -03:00
Writable.md Update documentation 2015-02-12 14:37:33 -02:00
Xdigit.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Yes.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03:00
Zend.md Standard for "See also:" on documentation 2015-08-20 01:38:41 -03: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

  • Repect\Validation\Exceptions\ExceptionInterface:
    • All exceptions implement this interface;
  • Respect\Validation\Exceptions\ValidationExceptionInterface:
    • Extends the Repect\Validation\Exceptions\ExceptionInterface interface
    • Use when calling check()
    • All validation exceptions implement this interface
    • Interface has one method: getMainMessage()
  • Respect\Validation\Exceptions\NestedValidationExceptionInterface:
    • Extends the Respect\Validation\Exceptions\ValidationExceptionInterface interface
    • Use when calling assert()
    • Interface has three methods: getFullMessage(), findMessages(), and getMainMessage().

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\NestedValidationExceptionInterface;

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

The printed message is exactly this, as a text tree:

\-All of the 3 required rules must pass
  |-"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

Requesting Messages

The text tree is fine, but unusable on a HTML form or something more custom. You can use findMessages() for that:

use Respect\Validation\Exceptions\NestedValidationExceptionInterface;

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

findMessages() returns an array with messages from the requested validators.

Getting Messages

Sometimes you just need all the messages, for that you can use getMessages(). It will return all messages from the rules that did not pass the validation.

try {
    Validator::key('username', Validator::length(2, 32))
             ->key('birthdate', Validator::date())
             ->key('password', Validator::notEmpty())
             ->key('email', Validator::email())
             ->assert($input);
} catch (NestedValidationExceptionInterface $e) {
    print_r($e->getMessages());
}

The code above may display something like:

Array
(
    [0] => username must have a length between 2 and 32
    [1] => birthdate must be a valid date
    [2] => password must not be empty
    [3] => Key email must be present
)

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}} and {{input}} variable is available for templates.

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 also can use your own rules:

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
    }
}

If you do want Validation to execute you 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\ValidationExceptionInterface;

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

Message:

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

See also: