Valitron Documentation

repository·master·Indexed 23 days ago

https://github.com/vlucas/valitron

A simple, minimal, and standalone PHP validation library with no dependencies. Valitron provides a concise syntax for validating data arrays, supporting built-in rules for dates, credit cards, and regex, as well as custom rule extension. It features dot notation for multi-dimensional arrays, conditional required rules, and customizable error messages with field labels.

Tokens
6.2K
Snippets
20
Records
39
Agent score
32%

What's inside Valitron

  1. Validate multi-dimensional arrays using dot syntax and asterisks

    master

    Valitron supports dot notation to access nested array members. You can use an asterisk (*) to apply a rule to every element in an array or every element within a nested array.

    // Validate threshold in nested settings array
    $v = new Valitron\Validator(array('settings' => array(
        array('threshold' => 50),
        array('threshold' => 90)
    )));
    $v->rule('max', 'settings.*.threshold', 100);
    
    // Validate all members of a numeric array
    $v = new Valitron\Validator(array('values' => array(50, 90)));
    $v->rule('max', 'values.*', 100);
    
    // Access nested values using dot notation
    $v = new Valitron\Validator(array('user' => array('first_name' => 'Steve', 'last_name' => 'Smith', 'username' => 'Batman123')));
    $v->rule('alpha', 'user.first_name')->rule('alpha', 'user.last_name')->rule('alphaNum', 'user.username');
  2. Use conditional required rules

    master

    Valitron allows you to conditionally require fields based on the presence of other fields using requiredWith and requiredWithout within the rules() method.

    // this rule set would work for either data set...
    $data = ['email' => 'test@test.com', 'password' => 'mypassword'];
    // or...
    $data = ['token' => 'jashdjahs83rufh89y38h38h'];
    
    $v = new Valitron\Validator($data);
    $v->rules([
        'requiredWithout' => [
            ['token', ['email', 'password'], true]
        ],
        'requiredWith' => [
            ['password', ['email']]
        ],
        'email' => [
            ['email']
        ],
        'optional' => [
            ['email']
        ]
    ]);
    $v->validate();
  3. Basic usage of Valitron

    master

    To use Valitron, instantiate Valitron\Validator with your data array, define rules using rule(), and call validate(). If validation fails, errors() returns an array of error messages.

    $v = new Valitron\Validator(array('name' => 'Chester Tester'));
    $v->rule('required', 'name');
    if($v->validate()) {
        echo "Yay! We're all good!";
    } else {
        // Errors
        print_r($v->errors());
    }
  4. Initialize the Valitron Validator

    master

    To use Valitron, instantiate the Valitron\Validator class. You can pass the data to be validated, an optional array of allowed fields to filter the input, and optional language settings.

    If you provide a $fields array, Valitron will only validate the intersection of the provided $data and the $fields keys. This is useful for sanitizing $_POST or $_GET data.

    Constructor Parameters

    • $data (array): The input data to validate.
    • $fields (array, optional): A list of allowed field names. Only these fields will be processed.
    • $lang (string, optional): The language code (e.g., 'en').
    • $langDir (string, optional): The directory containing language files.
  5. Validate multiple fields and $_POST data

    master

    You can pass an array of field names to a single rule to apply it to multiple fields at once. This is useful for validating $_POST or $_GET data directly.

    $v = new Valitron\Validator($_POST);
    $v->rule('required', ['name', 'email']);
    $v->rule('email', 'email');
    if($v->validate()) {
        echo "Yay! We're all good!";
    } else {
        // Errors
        print_r($v->errors());
    }
  6. Use the arrayHasKeys rule

    master

    The arrayHasKeys rule ensures that the field is an array and that it contains all the specified keys. It returns false if the field is not an array, if no keys are specified, or if any required key is missing.

    $v->rule('arrayHasKeys', 'address', ['name', 'street', 'city']);
  7. Configure the `requiredWith` rule

    master

    The requiredWith rule ensures a field is required (not null and not an empty string) if any of the specified other fields are present.

    You can provide a single field name or an array of field names. If an array is provided, the field is required if ANY of the fields in the array are present.

    // Required if 'username' is provided
    $v->rule('requiredWith', 'password', 'username');
    
    // Required if 'username' OR 'email' is provided
    $v->rule('requiredWith', 'password', ['username', 'email']);
    
    // Alternate syntax using rules()
    $v->rules([
        'requiredWith' => [
            ['password', ['username', 'email']]
        ]
    ]);
  8. Configure global language and directory

    master

    You can set the validation language and the directory containing language files globally using the static methods on the Validator class.

    use Valitron\Validator as V;
    
    V::langDir(__DIR__.'/validator_lang'); // always set langDir before lang.
    V::lang('ar');