SkillAgentSearch skills...

Valitron

Valitron is a simple, elegant, stand-alone validation library with NO dependencies

Install / Use

/learn @vlucas/Valitron
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

Valitron: Easy Validation That Doesn't Suck

Valitron is a simple, minimal and elegant stand-alone validation library with NO dependencies. Valitron uses simple, straightforward validation methods with a focus on readable and concise syntax. Valitron is the simple and pragmatic validation library you've been looking for.

Build
Status Latest Stable Version Total Downloads

Get supported vlucas/valitron with the Tidelift Subscription

Why Valitron?

Valitron was created out of frustration with other validation libraries that have dependencies on large components from other frameworks like Symfony's HttpFoundation, pulling in a ton of extra files that aren't really needed for basic validation. It also has purposefully simple syntax used to run all validations in one call instead of individually validating each value by instantiating new classes and validating values one at a time like some other validation libraries require.

In short, Valitron is everything you've been looking for in a validation library but haven't been able to find until now: simple pragmatic syntax, lightweight code that makes sense, extensible for custom callbacks and validations, well tested, and without dependencies. Let's get started.

Installation

Valitron uses Composer to install and update:

curl -s http://getcomposer.org/installer | php
php composer.phar require vlucas/valitron

The examples below use PHP 5.4 syntax, but Valitron works on PHP 5.3+.

Usage

Usage is simple and straightforward. Just supply an array of data you wish to validate, add some rules, and then call validate(). If there are any errors, you can call errors() to get them.

$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());
}

Using this format, you can validate $_POST data directly and easily, and can even apply a rule like required to an array of fields:

$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());
}

You may use dot syntax to access members of multi-dimensional arrays, and an asterisk to validate each member of an array:

$v = new Valitron\Validator(array('settings' => array(
    array('threshold' => 50),
    array('threshold' => 90)
)));
$v->rule('max', 'settings.*.threshold', 100);
if($v->validate()) {
    echo "Yay! We're all good!";
} else {
    // Errors
    print_r($v->errors());
}

Or use dot syntax to validate all members of a numeric array:

$v = new Valitron\Validator(array('values' => array(50, 90)));
$v->rule('max', 'values.*', 100);
if($v->validate()) {
    echo "Yay! We're all good!";
} else {
    // Errors
    print_r($v->errors());
}

You can also 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');
if($v->validate()) {
    echo "Yay! We're all good!";
} else {
    // Errors
    print_r($v->errors());
}

Setting language and language dir globally:


// boot or config file

use Valitron\Validator as V;

V::langDir(__DIR__.'/validator_lang'); // always set langDir before lang.
V::lang('ar');

Disabling the {field} name in the output of the error message.

use Valitron\Validator as V;

$v = new Valitron\Validator(['name' => 'John']);
$v->rule('required', ['name']);

// Disable prepending the labels
$v->setPrependLabels(false);

// Error output for the "false" condition
[
    ["name"] => [
        "is required"
    ]
]

// Error output for the default (true) condition
[
    ["name"] => [
        "name is required"
    ]
]

You can conditionally require values using required conditional rules. In this example, for authentication, we're requiring either a token when both the email and password are not present, or a password when the email address is present.

// 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']
    ]
]);
$this->assertTrue($v->validate());

Built-in Validation Rules

  • required - Field is required
  • requiredWith - Field is required if any other fields are present
  • requiredWithout - Field is required if any other fields are NOT present
  • equals - Field must match another field (email/password confirmation)
  • different - Field must be different than another field
  • accepted - Checkbox or Radio must be accepted (yes, on, 1, true)
  • numeric - Must be numeric
  • integer - Must be integer number
  • boolean - Must be boolean
  • array - Must be array
  • length - String must be certain length
  • lengthBetween - String must be between given lengths
  • lengthMin - String must be greater than given length
  • lengthMax - String must be less than given length
  • min - Minimum
  • max - Maximum
  • listContains - Performs in_array check on given array values (the other way round than in)
  • in - Performs in_array check on given array values
  • notIn - Negation of in rule (not in array of values)
  • ip - Valid IP address
  • ipv4 - Valid IP v4 address
  • ipv6 - Valid IP v6 address
  • email - Valid email address
  • emailDNS - Valid email address with active DNS record
  • url - Valid URL
  • urlActive - Valid URL with active DNS record
  • alpha - Alphabetic characters only
  • alphaNum - Alphabetic and numeric characters only
  • ascii - ASCII characters only
  • slug - URL slug characters (a-z, 0-9, -, _)
  • regex - Field matches given regex pattern
  • date - Field is a valid date
  • dateFormat - Field is a valid date in the given format
  • dateBefore - Field is a valid date and is before the given date
  • dateAfter - Field is a valid date and is after the given date
  • contains - Field is a string and contains the given string
  • subset - Field is an array or a scalar and all elements are contained in the given array
  • containsUnique - Field is an array and contains unique values
  • creditCard - Field is a valid credit card number
  • instanceOf - Field contains an instance of the given class
  • optional - Value does not need to be included in data array. If it is however, it must pass validation.
  • arrayHasKeys - Field is an array and contains all specified keys.

NOTE: If you are comparing floating-point numbers with min/max validators, you should install the BCMath extension for greater accuracy and reliability. The extension is not required for Valitron to work, but Valitron will use it if available, and it is highly recommended.

required fields usage

the required rule checks if a field exists in the data array, and is not null or an empty string.

$v->rule('required', 'field_name');

Using an extra parameter, you can make this rule more flexible, and only check if the field exists in the data array.

$v->rule('required', 'field_name', true);

Alternate syntax.

$v = new Valitron\Validator(['username' => 'spiderman', 'password' => 'Gr33nG0Blin', 'required_but_null' => null]);
$v->rules([
    'required' => [
        ['username'],
        ['password'],
        ['required_but_null', true] // boolean flag allows empty value so long as the field name is set on the data array
    ]
]);
$v->validate();

requiredWith fields usage

The requiredWith rule checks that the field is required, not null, and not the empty string, if any other fields are present, not null, and not the empty string.

// password field will be required when the username field is provided and not empty
$v->rule('requiredWith', 'password', 'username');

Alternate syntax.

$v = new Valitron\Validator(['username' => 'spiderman', 'password' => 'Gr33nG0Blin']);
$v->rules([
    'requiredWith' => [
        ['password', 'username']
    ]
]);
$v->validate();

Note You can provide multiple values as an array. In this case if ANY of the fields are present the field will be required.

// in this case the password field will be required if the username or email fields are present
$v->rule('requiredWith', 'password', ['username', 'email']);

Alternate syntax.

$v = new Valitron\Validator(['username' => 'spiderman', 'password' => 'Gr33nG0Blin']);
$v->rules([
    'requiredWith' => [
        ['password', ['username', 'email']]
    ]
]);
$v->validate();

Strict flag

The strict flag will change the requiredWith rule to requiredWithAll which will require the field only if ALL of the other fields are present, not null, and not the empty string.

// in this example the suffix field is required only when both the first_name and last_name are provided
$v->rule('requiredWith', 'suffix', ['first_name', 'last_name'], true);

Alt

Related Skills

View on GitHub
GitHub Stars1.6k
CategoryDevelopment
Updated3d ago
Forks250

Languages

PHP

Security Score

100/100

Audited on Mar 30, 2026

No findings