Sirius Validation
Sirius Validation is a library for data validation. It offers:
- validator object
- 45 build-in validation rules. There are validators for strings, array, numbers, emails, URLs, files and uploads
- validation helper to simplify the validation of single values
Out-of-the-box, the library can handle array
s, ArrayObject
s and objects that have implemented the toArray
method.
In order to validate other data containers you must create a DataWrapper
so that the validator be able to extract data from your object.
Elevator pitch
$validation = new \Sirius\Validation\Validator;
// let's validate an invoice form
$validator->add(array(
// :Date specifies the label for the field. It will be used in the error messages
'order_date:Date' => 'required | date',
// `clientexists` is an app-specific rule
'client_id:Client' => 'required | clientexists',
// apply the same rule for an array of items
'notify_recipients[*]:Send invoice to' => 'email',
// apply a rule to a specific item in the array
'shipping_address[line_1]:Address' => 'required'
'shipping_address[city]:City' => 'required'
'shipping_address[state]:State' => 'required'
'shipping_address[country]:Country' => 'required',
'lines[*]price:Price' => [
// the price is required only if a product was selected
'requiredWith(item=lines[*]product_id)',
// another app-specific rule applied to the price, specified as a class
'MyApp\Validator\Rule\InvoiceItemPrice'
];,
'lines[*]quantity:Quantity' => [
// the price is required only if a product was selected
'requiredWith(item=lines[*]product_id)',
// here we have a custom validation rule with no parameters AND a custom error message
'quantity_in_stock()(The quantity is not valid)'
;
)
));
Why this style?
-
Because I want to be able to do the following in my views
<div class="error"> <?php echo $messages['lines[0][price]']; ?> </div>
This may seem counter-productive but remember that your forms' input fields may look like this
<input name="lines[0][price]" value="abc">
-
Because, If I am to do server side validation I can receive a JSON
{ "errors": { "recipients[0]": "Field must be a valid email", "lines[2][price]": "Price must be a number", } }
This way I can find the corresponding HTML inputs and show the error
$.each(errors, function(message, field) { $('[name="' + field + '"]') .parents('div.control') .addClass('error') .append('<div class="error">'+message+'</div>'); });
-
If I am to do client-side validation I want to do the following
<script> <?php $clientSideRules = $helperThatCompilesTheClientSideValidation->getValidationRules($validator); ?> $('#myForm').validate(<?php echo json_encode($clientSideRules))?>); </script>