Valitron
Valitron is a simple, elegant, stand-alone validation library with NO dependencies
Install / Use
/learn @vlucas/ValitronREADME
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.
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 requiredrequiredWith- Field is required if any other fields are presentrequiredWithout- Field is required if any other fields are NOT presentequals- Field must match another field (email/password confirmation)different- Field must be different than another fieldaccepted- Checkbox or Radio must be accepted (yes, on, 1, true)numeric- Must be numericinteger- Must be integer numberboolean- Must be booleanarray- Must be arraylength- String must be certain lengthlengthBetween- String must be between given lengthslengthMin- String must be greater than given lengthlengthMax- String must be less than given lengthmin- Minimummax- MaximumlistContains- Performs in_array check on given array values (the other way round thanin)in- Performs in_array check on given array valuesnotIn- Negation ofinrule (not in array of values)ip- Valid IP addressipv4- Valid IP v4 addressipv6- Valid IP v6 addressemail- Valid email addressemailDNS- Valid email address with active DNS recordurl- Valid URLurlActive- Valid URL with active DNS recordalpha- Alphabetic characters onlyalphaNum- Alphabetic and numeric characters onlyascii- ASCII characters onlyslug- URL slug characters (a-z, 0-9, -, _)regex- Field matches given regex patterndate- Field is a valid datedateFormat- Field is a valid date in the given formatdateBefore- Field is a valid date and is before the given datedateAfter- Field is a valid date and is after the given datecontains- Field is a string and contains the given stringsubset- Field is an array or a scalar and all elements are contained in the given arraycontainsUnique- Field is an array and contains unique valuescreditCard- Field is a valid credit card numberinstanceOf- Field contains an instance of the given classoptional- 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
node-connect
345.9kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
106.4kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
345.9kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
345.9kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。


