title |
---|
The validation rules factory |
Every validator object uses a RuleFactory
to construct the validation rules based on the parameters received by the add()
method.
The RuleFactory
is a simple registry-like object which stores
- the names of validation rules and their corresponding validation rules classes.
- the default error messages for each validation rule. These are used when there is NO label attached to the field
- the default LABELED error messages for each validation rule. These are used when the field has a label attached
By configuring the default error messages in the RuleFactory
you don't have to repeat yourself. Since you should use a single RuleFactory
for the entire app, there will be a single place where you can set the error message for, let's say, the required
rule.
!!! Important !!! The error messages are optional because each validation rule class has constants which define the default error messages for that class.
The code below assumes you got a handle of the $validationFactory from a registry or dependency injection container.
use Sirius\Validation\RuleFactory;
$ruleFactory = new RuleFactory;
// register new validation class
$ruleFactory->register('user_exists', 'MyApp\UserExistsValidator', $defaultMessageWithoutLabel, $defaultMessageWithLabel);
// overwrite an already registered class
$ruleFactory->register('email', 'MyApp\VeryPowerfullEmailValidator', $defaultMessageWithoutLabel, $defaultMessageWithLabel);
// override just the error messages
$ruleFactory->setMessages('email', $defaultMessageWithoutLabel, $defaultMessageWithLabel);
// obviously you can override only what you need
$ruleFactory->setMessages('email', null, $defaultMessageWithLabel);
If you omit this step you will end up using a regular (ie: non-custom) RuleFactory
instance
use Sirius\Validation\Validator;
$validator = new Validator($ruleFactory);