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

Overview

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' => '[email protected]', '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);

Alternate syntax.

$v = new Valitron\Validator(['first_name' => 'steve', 'last_name' => 'holt', 'suffix' => 'Mr']);
$v->rules([
    'requiredWith' => [
        ['suffix', ['first_name', 'last_name'], true]
    ]
]);
$v->validate();

Likewise, in this case validate() would still return true, as the suffix field would not be required in strict mode, as not all of the fields are provided.

$v = new Valitron\Validator(['first_name' => 'steve']);
$v->rules([
    'requiredWith' => [
        ['suffix', ['first_name', 'last_name'], true]
    ]
]);
$v->validate();

requiredWithout fields usage

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

// this rule will require the username field when the first_name is not present
$v->rule('requiredWithout', 'username', 'first_name')

Alternate syntax.

// this will return true, as the username is provided when the first_name is not provided
$v = new Valitron\Validator(['username' => 'spiderman']);
$v->rules([
    'requiredWithout' => [
        ['username', 'first_name']
    ]
]);
$v->validate();

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

// in this case the username field will be required if either the first_name or last_name fields are not present
$v->rule('requiredWithout', 'username', ['first_name', 'last_name']);

Alternate syntax.

// this passes validation because although the last_name field is not present, the username is provided
$v = new Valitron\Validator(['username' => 'spiderman', 'first_name' => 'Peter']);
$v->rules([
    'requiredWithout' => [
        ['username', ['first_name', 'last_name']]
    ]
]);
$v->validate();

Strict flag

The strict flag will change the requiredWithout rule to requiredWithoutAll which will require the field only if ALL of the other fields are not present.

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

Alternate syntax.

$v = new Valitron\Validator(['username' => 'BatMan']);
$v->rules([
    'requiredWithout' => [
        ['username', ['first_name', 'last_name'], true]
    ]
]);
$v->validate();

Likewise, in this case validate() would still return true, as the username field would not be required in strict mode, as all of the fields are provided.

$v = new Valitron\Validator(['first_name' => 'steve', 'last_name' => 'holt']);
$v->rules([
    'requiredWithout' => [
        ['suffix', ['first_name', 'last_name'], true]
    ]
]);
$v->validate();

equals fields usage

The equals rule checks if two fields are equals in the data array, and that the second field is not null.

$v->rule('equals', 'password', 'confirmPassword');

Alternate syntax.

$v = new Valitron\Validator(['password' => 'youshouldnotseethis', 'confirmPassword' => 'youshouldnotseethis']);
$v->rules([
    'equals' => [
        ['password', 'confirmPassword']
    ]
]);
$v->validate();

different fields usage

The different rule checks if two fields are not the same, or different, in the data array and that the second field is not null.

$v->rule('different', 'username', 'password');

Alternate syntax.

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

accepted fields usage

The accepted rule checks if the field is either 'yes', 'on', 1, or true.

$v->rule('accepted', 'remember_me');

Alternate syntax.

$v = new Valitron\Validator(['remember_me' => true]);
$v->rules([
    'accepted' => [
        ['remember_me']
    ]
]);
$v->validate();

numeric fields usage

The numeric rule checks if the field is number. This is analogous to php's is_numeric() function.

$v->rule('numeric', 'amount');

Alternate syntax.

$v = new Valitron\Validator(['amount' => 3.14]);
$v->rules([
    'numeric' => [
        ['amount']
    ]
]);
$v->validate();

integer fields usage

The integer rule checks if the field is an integer number.

$v->rule('integer', 'age');

Alternate syntax.

$v = new Valitron\Validator(['age' => '27']);
$v->rules([
    'integer' => [
        ['age']
    ]
]);
$v->validate();

Note the optional boolean flag for strict mode makes sure integers are to be supplied in a strictly numeric form. So the following rule would evaluate to true:

$v = new Valitron\Validator(['negative' => '-27', 'positive'=>'27']);
$v->rule('integer', 'age', true);
$v->rule('integer', 'height', true);
$v->validate();

Whereas the following will evaluate to false, as the + for the positive number in this case is redundant:

$v = new Valitron\Validator(['negative' => '-27', 'positive'=>'+27']);
$v->rule('integer', 'age', true);
$v->rule('integer', 'height', true);
$v->validate();

boolean fields usage

The boolean rule checks if the field is a boolean. This is analogous to php's is_bool() function.

$v->rule('boolean', 'remember_me');

Alternate syntax.

$v = new Valitron\Validator(['remember_me' => true]);
$v->rules([
    'boolean' => [
        ['remember_me']
    ]
]);
$v->validate();

array fields usage

The array rule checks if the field is an array. This is analogous to php's is_array() function.

$v->rule('array', 'user_notifications');

Alternate Syntax.

$v = new Valitron\Validator(['user_notifications' => ['bulletin_notifications' => true, 'marketing_notifications' => false, 'message_notification' => true]]);
$v->rules([
    'array' => [
        ['user_notifications']
    ]
]);
$v->validate();

length fields usage

The length rule checks if the field is exactly a given length and that the field is a valid string.

$v->rule('length', 'username', 10);

Alternate syntax.

$v = new Valitron\Validator(['username' => 'bobburgers']);
$v->rules([
    'length' => [
        ['username', 10]
    ]
]);
$v->validate();

lengthBetween fields usage

The lengthBetween rule checks if the field is between a given length tange and that the field is a valid string.

$v->rule('lengthBetween', 'username', 1, 10);

Alternate syntax.

$v = new Valitron\Validator(['username' => 'bobburgers']);
$v->rules([
    'lengthBetween' => [
        ['username', 1, 10]
    ]
]);
$v->validate();

lengthMin fields usage

The lengthMin rule checks if the field is at least a given length and that the field is a valid string.

$v->rule('lengthMin', 'username', 5);

Alternate syntax.

$v = new Valitron\Validator(['username' => 'martha']);
$v->rules([
    'lengthMin' => [
        ['username', 5]
    ]
]);
$v->validate();

lengthMax fields usage

The lengthMax rule checks if the field is at most a given length and that the field is a valid string.

$v->rule('lengthMax', 'username', 10);

Alternate syntax.

$v = new Valitron\Validator(['username' => 'bruins91']);
$v->rules([
    'lengthMax' => [
        ['username', 10]
    ]
]);
$v->validate();

min fields usage

The min rule checks if the field is at least a given value and that the provided value is numeric.

$v->rule('min', 'age', 18);

Alternate syntax.

$v = new Valitron\Validator(['age' => 28]);
$v->rules([
    'min' => [
        ['age', 18]
    ]
]);
$v->validate();

max fields usage

The max rule checks if the field is at most a given value and that the provided value is numeric.

$v->rule('max', 'age', 12);

Alternate syntax.

$v = new Valitron\Validator(['age' => 10]);
$v->rules([
    'max' => [
        ['age', 12]
    ]
]);
$v->validate();

listContains fields usage

The listContains rule checks that the field is present in a given array of values.

$v->rule('listContains', 'color', 'yellow');

Alternate syntax.

$v = new Valitron\Validator(['color' => ['blue', 'green', 'red', 'yellow']]);
$v->rules([
    'listContains' => [
        ['color', 'yellow']
    ]
]);
$v->validate();

in fields usage

The in rule checks that the field is present in a given array of values.

$v->rule('in', 'color', ['blue', 'green', 'red', 'purple']);

Alternate syntax.

$v = new Valitron\Validator(['color' => 'purple']);
$v->rules([
    'in' => [
        ['color', ['blue', 'green', 'red', 'purple']]
    ]
]);
$v->validate();

notIn fields usage

The notIn rule checks that the field is NOT present in a given array of values.

$v->rule('notIn', 'color', ['blue', 'green', 'red', 'yellow']);

Alternate syntax.

$v = new Valitron\Validator(['color' => 'purple']);
$v->rules([
    'notIn' => [
        ['color', ['blue', 'green', 'red', 'yellow']]
    ]
]);
$v->validate();

ip fields usage

The ip rule checks that the field is a valid ip address. This includes IPv4, IPv6, private, and reserved ranges.

$v->rule('ip', 'user_ip');

Alternate syntax.

$v = new Valitron\Validator(['user_ip' => '127.0.0.1']);
$v->rules([
    'ip' => [
        ['user_ip']
    ]
]);
$v->validate();

ipv4 fields usage

The ipv4 rule checks that the field is a valid IPv4 address.

$v->rule('ipv4', 'user_ip');

Alternate syntax.

$v = new Valitron\Validator(['user_ip' => '127.0.0.1']);
$v->rules([
    'ipv4' => [
        ['user_ip']
    ]
]);
$v->validate();

ipv6 fields usage

The ipv6 rule checks that the field is a valid IPv6 address.

$v->rule('ipv6', 'user_ip');

Alternate syntax.

$v = new Valitron\Validator(['user_ip' => '0:0:0:0:0:0:0:1']);
$v->rules([
    'ipv6' => [
        ['user_ip']
    ]
]);
$v->validate();

email fields usage

The email rule checks that the field is a valid email address.

$v->rule('email', 'user_email');

Alternate syntax.

$v = new Valitron\Validator(['user_email' => '[email protected]']);
$v->rules([
    'email' => [
        ['user_email']
    ]
]);
$v->validate();

emailDNS fields usage

The emailDNS rule validates the field is a valid email address with an active DNS record or any type.

$v->rule('emailDNS', 'user_email');

Alternate syntax.

$v = new Valitron\Validator(['user_email' => '[email protected]']);
$v->rules([
    'emailDNS' => [
        ['user_email']
    ]
]);
$v->validate();

url fields usage

The url rule checks the field is a valid url.

$v->rule('url', 'website');

Alternate syntax.

$v = new Valitron\Validator(['website' => 'https://example.com/contact']);
$v->rules([
    'url' => [
        ['website']
    ]
]);
$v->validate();

urlActive fields usage

The urlActive rule checks the field is a valid url with an active A, AAAA, or CNAME record.

$v->rule('urlActive', 'website');

Alternate syntax.

$v = new Valitron\Validator(['website' => 'https://example.com/contact']);
$v->rules([
    'urlActive' => [
        ['website']
    ]
]);
$v->validate();

alpha fields usage

The alpha rule checks the field is alphabetic characters only.

$v->rule('alpha', 'username');

Alternate syntax.

$v = new Valitron\Validator(['username' => 'batman']);
$v->rules([
    'alpha' => [
        ['username']
    ]
]);
$v->validate();

alphaNum fields usage

The alphaNum rule checks the field contains only alphabetic or numeric characters.

$v->rule('alphaNum', 'username');

Alternate syntax.

$v = new Valitron\Validator(['username' => 'batman123']);
$v->rules([
    'alphaNum' => [
        ['username']
    ]
]);
$v->validate();

ascii fields usage

The ascii rule checks the field contains only characters in the ascii character set.

$v->rule('ascii', 'username');

Alternate syntax.

$v = new Valitron\Validator(['username' => 'batman123']);
$v->rules([
    'ascii' => [
        ['username']
    ]
]);
$v->validate();

slug fields usage

The slug rule checks that the field only contains URL slug characters (a-z, 0-9, -, _).

$v->rule('slug', 'username');

Alternate syntax.

$v = new Valitron\Validator(['username' => 'L337-H4ckZ0rz_123']);
$v->rules([
    'slug' => [
        ['username']
    ]
]);
$v->validate();

regex fields usage

The regex rule ensures the field matches a given regex pattern. (This regex checks the string is alpha numeric between 5-10 characters).

$v->rule('regex', 'username', '/^[a-zA-Z0-9]{5,10}$/');

Alternate syntax.

$v = new Valitron\Validator(['username' => 'Batman123']);
$v->rules([
    'regex' => [
        ['username', '/^[a-zA-Z0-9]{5,10}$/']
    ]
]);
$v->validate();

date fields usage

The date rule checks if the supplied field is a valid \DateTime object or if the string can be converted to a unix timestamp via strtotime().

$v->rule('date', 'created_at');

Alternate syntax.

$v = new Valitron\Validator(['created_at' => '2018-10-13']);
$v->rules([
    'date' => [
        ['created_at']
    ]
]);
$v->validate();

dateFormat fields usage

The dateFormat rule checks that the supplied field is a valid date in a specified date format.

$v->rule('dateFormat', 'created_at', 'Y-m-d');

Alternate syntax.

$v = new Valitron\Validator(['created_at' => '2018-10-13']);
$v->rules([
    'dateFormat' => [
        ['created_at', 'Y-m-d']
    ]
]);
$v->validate();

dateBefore fields usage

The dateBefore rule checks that the supplied field is a valid date before a specified date.

$v->rule('dateBefore', 'created_at', '2018-10-13');

Alternate syntax.

$v = new Valitron\Validator(['created_at' => '2018-09-01']);
$v->rules([
    'dateBefore' => [
        ['created_at', '2018-10-13']
    ]
]);
$v->validate();

dateAfter fields usage

The dateAfter rule checks that the supplied field is a valid date after a specified date.

$v->rule('dateAfter', 'created_at', '2018-10-13');

Alternate syntax.

$v = new Valitron\Validator(['created_at' => '2018-09-01']);
$v->rules([
    'dateAfter' => [
        ['created_at', '2018-01-01']
    ]
]);
$v->validate();

contains fields usage

The contains rule checks that a given string exists within the field and checks that the field and the search value are both valid strings.

$v->rule('contains', 'username', 'man');

Alternate syntax.

$v = new Valitron\Validator(['username' => 'Batman123']);
$v->rules([
    'contains' => [
        ['username', 'man']
    ]
]);
$v->validate();

Note You can use the optional strict flag to ensure a case-sensitive match. The following example will return true:

$v = new Valitron\Validator(['username' => 'Batman123']);
$v->rules([
    'contains' => [
        ['username', 'man']
    ]
]);
$v->validate();

Whereas, this would return false, as the M in the search string is not uppercase in the provided value:

$v = new Valitron\Validator(['username' => 'Batman123']);
$v->rules([
    'contains' => [
        ['username', 'Man', true]
    ]
]);
$v->validate();

subset fields usage

The subset rule checks that the field is either a scalar or array field and that all of it's values are contained within a given set of values.

$v->rule('subset', 'colors', ['green', 'blue', 'orange']);

Alternate syntax.

$v = new Valitron\Validator(['colors' => ['green', 'blue']]);
$v->rules([
    'subset' => [
        ['colors', ['orange', 'green', 'blue', 'red']]
    ]
]);
$v->validate();

This example would return false, as the provided color, purple, does not exist in the array of accepted values we're providing.

$v = new Valitron\Validator(['colors' => ['purple', 'blue']]);
$v->rules([
    'subset' => [
        ['colors', ['orange', 'green', 'blue', 'red']]
    ]
]);
$v->validate();

containsUnique fields usage

The containsUnique rule checks that the provided field is an array and that all values contained within are unique, i.e. no duplicate values in the array.

$v->rule('containsUnique', 'colors');

Alternate syntax.

$v = new Valitron\Validator(['colors' => ['purple', 'blue']]);
$v->rules([
    'containsUnique' => [
        ['colors']
    ]
]);
$v->validate();

This example would return false, as the values in the provided array are duplicates.

$v = new Valitron\Validator(['colors' => ['purple', 'purple']]);
$v->rules([
    'containsUnique' => [
        ['colors']
    ]
]);
$v->validate();

Credit Card Validation usage

Credit card validation currently allows you to validate a Visa visa, Mastercard mastercard, Dinersclub dinersclub, American Express amex or Discover discover

This will check the credit card against each card type

$v->rule('creditCard', 'credit_card');

To optionally filter card types, add the slug to an array as the next parameter:

$v->rule('creditCard', 'credit_card', ['visa', 'mastercard']);

If you only want to validate one type of card, put it as a string:

$v->rule('creditCard', 'credit_card', 'visa');

If the card type information is coming from the client, you might also want to still specify an array of valid card types:

$cardType = 'amex';
$v->rule('creditCard', 'credit_card', $cardType, ['visa', 'mastercard']);
$v->validate(); // false

instanceOf fields usage

The instanceOf rule checks that the field is an instance of a given class.

$v->rule('instanceOf', 'date', \DateTime);

Alternate syntax.

$v = new Valitron\Validator(['date' => new \DateTime()]);
$v->rules([
    'instanceOf' => [
        ['date', 'DateTime']
    ]
]);
$v->validate();

Note You can also compare the value against a given object as opposed to the string class name. This example would also return true:

$v = new Valitron\Validator(['date' => new \DateTime()]);
$existingDateObject = new \DateTime();
$v->rules([
    'instanceOf' => [
        ['date', $existingDateObject]
    ]
]);
$v->validate();

optional fields usage

The optional rule ensures that if the field is present in the data set that it passes all validation rules.

$v->rule('optional', 'username');

Alternate syntax. This example would return true either when the 'username' field is not present or in the case where the username is only alphabetic characters.

$v = new Valitron\Validator(['username' => 'batman']);
$v->rules([
    'alpha' => [
        ['username']
    ],
    'optional' => [
        ['username']
    ]
]);
$v->validate();

This example would return false, as although the field is optional, since it is provided it must pass all the validation rules, which in this case it does not.

$v = new Valitron\Validator(['username' => 'batman123']);
$v->rules([
    'alpha' => [
        ['username']
    ],
    'optional' => [
        ['username']
    ]
]);
$v->validate();

arrayHasKeys fields usage

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

$v = new Valitron\Validator([
    'address' => [
        'name' => 'Jane Doe',
        'street' => 'Doe Square',
        'city' => 'Doe D.C.'
    ]
]);
$v->rule('arrayHasKeys', 'address', ['name', 'street', 'city']);
$v->validate();

Adding Custom Validation Rules

To add your own validation rule, use the addRule method with a rule name, a custom callback or closure, and a error message to display in case of an error. The callback provided should return boolean true or false.

Valitron\Validator::addRule('alwaysFail', function($field, $value, array $params, array $fields) {
    return false;
}, 'Everything you do is wrong. You fail.');

You can also use one-off rules that are only valid for the specified fields.

$v = new Valitron\Validator(array("foo" => "bar"));
$v->rule(function($field, $value, $params, $fields) {
    return true;
}, "foo")->message("{field} failed...");

This is useful because such rules can have access to variables defined in the scope where the Validator lives. The Closure's signature is identical to Validator::addRule callback's signature.

If you wish to add your own rules that are not static (i.e., your rule is not static and available to call Validator instances), you need to use Validator::addInstanceRule. This rule will take the same parameters as Validator::addRule but it has to be called on a Validator instance.

Chaining rules

You can chain multiple rules together using the following syntax.

$v = new Valitron\Validator(['email_address' => '[email protected]']);
$v->rule('required', 'email_address')->rule('email', 'email_address');
$v->validate();

Alternate syntax for adding rules

As the number of rules grows, you may prefer the alternate syntax for defining multiple rules at once.

$rules = [
    'required' => 'foo',
    'accepted' => 'bar',
    'integer' =>  'bar'
];

$v = new Valitron\Validator(array('foo' => 'bar', 'bar' => 1));
$v->rules($rules);
$v->validate();

If your rule requires multiple parameters or a single parameter more complex than a string, you need to wrap the rule in an array.

$rules = [
    'required' => [
        ['foo'],
        ['bar']
    ],
    'length' => [
        ['foo', 3]
    ]
];

You can also specify multiple rules for each rule type.

$rules = [
    'length'   => [
        ['foo', 5],
        ['bar', 5]
    ]
];

Putting these techniques together, you can create a complete rule definition in a relatively compact data structure.

You can continue to add individual rules with the rule method even after specifying a rule definition via an array. This is especially useful if you are defining custom validation rules.

$rules = [
    'required' => 'foo',
    'accepted' => 'bar',
    'integer' =>  'bar'
];

$v = new Valitron\Validator(array('foo' => 'bar', 'bar' => 1));
$v->rules($rules);
$v->rule('min', 'bar', 0);
$v->validate();

You can also add rules on a per-field basis:

$rules = [
    'required',
    ['lengthMin', 4]
];

$v = new Valitron\Validator(array('foo' => 'bar'));
$v->mapFieldRules('foo', $rules);
$v->validate();

Or for multiple fields at once:

$rules = [
    'foo' => ['required', 'integer'],
    'bar'=>['email', ['lengthMin', 4]]
];

$v = new Valitron\Validator(array('foo' => 'bar', 'bar' => '[email protected]));
$v->mapFieldsRules($rules);
$v->validate();

Adding field label to messages

You can do this in two different ways, you can add a individual label to a rule or an array of all labels for the rules.

To add individual label to rule you simply add the label method after the rule.

$v = new Valitron\Validator(array());
$v->rule('required', 'name')->message('{field} is required')->label('Name');
$v->validate();

There is a edge case to this method, you wouldn't be able to use a array of field names in the rule definition, so one rule per field. So this wouldn't work:

$v = new Valitron\Validator(array());
$v->rule('required', array('name', 'email'))->message('{field} is required')->label('Name');
$v->validate();

However we can use a array of labels to solve this issue by simply adding the labels method instead:

$v = new Valitron\Validator(array());
$v->rule('required', array('name', 'email'))->message('{field} is required');
$v->labels(array(
    'name' => 'Name',
    'email' => 'Email address'
));
$v->validate();

This introduces a new set of tags to your error language file which looks like {field}, if you are using a rule like equals you can access the second value in the language file by incrementing the field with a value like {field1}.

Re-use of validation rules

You can re-use your validation rules to quickly validate different data with the same rules by using the withData method:

$v = new Valitron\Validator(array());
$v->rule('required', 'name')->message('{field} is required');
$v->validate(); //false

$v2 = $v->withData(array('name'=>'example'));
$v2->validate(); //true

Running Tests

The test suite depends on the Composer autoloader to load and run the Valitron files. Please ensure you have downloaded and installed Composer before running the tests:

  1. Download Composer curl -s http://getcomposer.org/installer | php
  2. Run 'install' php composer.phar install
  3. Run the tests phpunit

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Make your changes
  4. Run the tests, adding new ones for your own code if necessary (phpunit)
  5. Commit your changes (git commit -am 'Added some feature')
  6. Push to the branch (git push origin my-new-feature)
  7. Create new Pull Request
  8. Pat yourself on the back for being so awesome

Security Disclosures and Contact Information

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

Comments
  • Array Validation

    Array Validation

    How would you do array validation?

    Say I have this input:

    $_POST = [
        'users' => [
            7 => '[email protected]',
            12 => '[email protected]',
        ]
    ];
    

    I want to validate that the users key exists in $_POST, and its value is an array.

    Then for each key of the users array, I want to validate the key is a user ID (callback).

    Then for each value of the users array, I want to validate that the value is an email address.

    Is this possible with this library? If so, how?

    opened by Petah 24
  • Wrong assoc array detection

    Wrong assoc array detection

    In validateIn and validateListContains method threats non-sequential array as associative.

    1. [0 => 'A', 1 => 'B', 2 => 'C'] is an indexed array with sequential indexes
    2. [1 => 'A', 2 => 'B', 3 => 'C'] is an indexed array with non-sequential indexes
    3. ['0' => 'A', '1' => 'B', '2' => 'C'] is an associative array with numeric keys
    4. ['a' => 'A', 'b' => 'B', 'c' => 'C'] is an associative array with string keys

    Maybe you should soften the check of the associative array?

    return count(array_filter(array_keys($array), 'is_string')) > 0
    

    https://stackoverflow.com/a/4254008

    The array_diff function and the array_intersect function preserve keys, so the indexed array suddenly turns into an associative array.

    question 
    opened by eugene-borovov 14
  • Added dependent validations.

    Added dependent validations.

    Ability to attach several rules to another rule only be validated if the parent rule passes.

    Example: You want to validate that a user has included their credit card number if their age exceeds 18, so you could do something like this:

    $this->rule('min', 'age', 18)
        ->chain('required', 'credit_card')
        ->chain('creditCard', 'credit_card')
    

    This pull request only supports adding a single leveling of chaining with the helper functions. But the validateChain function could recurse infinitely if deeper chains were added.

    opened by wleona3 14
  • Custom callback validation against array

    Custom callback validation against array

    I have been trying to add a custom rule using "addRule" which uses an array as an extra parameter.

    This is what I am validating with

    $v->addRule('validNewsletter', array($this, 'validNewsletters'));
    $valid_keys = array('news','sport');
    $v->rule('validNewsletter', 'newsletters', $valid_keys)->message('Invalid newsletter selected.');
    

    Unfortunately this currently breaks on line 611 of the Validator class

    $label = isset($params[$k]) && isset($this->_labels[$params[$k]]) ? $this->_labels[$params[$k]] : $tag;
    

    It complains that the isset value is not a string

    Could this line be changed to this - which does work in this use case?

    $label = isset($params[$k]) && !is_array($params[$k]) && isset($this->_labels[$params[$k]]) ? $this->_labels[$params[$k]] : $tag;
    
    opened by seandowney 13
  • Improved the email validator by making sure the domain name is valid.

    Improved the email validator by making sure the domain name is valid.

    The validateEmail() method now does the following:

    1. Performs a filter_var() check with the FILTER_VALIDATE_EMAIL flag
    2. Extracts a fully qualified ASCII domain name from the email address
    3. Checks to make sure that the domain has a DNS record

    This doesn't guarantee that the email account is valid (which is impossible), but it will check to make sure that the domain exists and has DNS entries. It doesn't look for MX entries in particular because it's possible they may not be present for certain domains, though email is sent using them.

    opened by jabarihunt 12
  • If required is not set, empty field is not validated if needed

    If required is not set, empty field is not validated if needed

    Hi,

    in validate() function is if statement which removes validation if there is not "required" field set on it as one of many rules.

    Imagine that: Using REST, user can update something database and on update, (for example) element_name is not required field. BUT, if users uses it as parameter to update, its length must be at least 5 characters.

    Using this library, this is now not possible. 2 issues are:

    1. I need to set "required" and if user don't want to update it, error is thrown,
    2. If I don't set "required" and parameter is empty {"element_name":""}, validation will pass even if I set lengthMin to 5.

    This should be fixed in validate() function.

    opened by MaJerle 11
  • Issue #1 tests and code to support adding multiple rules via an array

    Issue #1 tests and code to support adding multiple rules via an array

    I have made progress, but I need some feedback. This is not ready to merge yet.

    Look at my last test and you will see that it is losing the last field in the required definition. The reason for this is because I'm merging params down into an array before calling the rule() method. In this case, we don't want rule('required', 'missing_field_1', 'missing_field_2') we want rule('required', array('missing_field_1', 'missing_field_2')).

    I can think of two approaches to solving this:

    1. Add a switch case to set which rule types have additional params and which don't (like the required type).
    2. Use reflection to look up the validate method for that rule type and see if it accepts a $params option.

    Thoughts?

    opened by joelclermont 11
  • Email validation - including mail domain check

    Email validation - including mail domain check

    Hi,

    while discussing email validation in userfrosting/fortress to include a check for the existence of actual email domain using a DNS look up for MX record that would confirm that the email domain is indeed valid (https://github.com/userfrosting/UserFrosting/issues/467) Alex Weissman suggested updating email validation in valitron.

    So, I had modified Valitron\Validator.php validateEmail() as follows to include a domain check as follows: /** * Validate that a field is a valid e-mail address * * @param string $field * @param mixed $value * @return bool */ protected function validateEmail($field, $value) { // validate email pattern and domain list($user, $domain) = split('@', $value); return (checkdnsrr($domain, 'MX') && (filter_var($value, \FILTER_VALIDATE_EMAIL) !== false) ); }

    This accepts only valid email domains.

    Would request to kindly consider for inclusion if you think it is worthwhile.

    Thanks! Spurgeon

    opened by spurgeonbj 10
  • PHP Versions (please comment here if you use Valitron)

    PHP Versions (please comment here if you use Valitron)

    As you can see in the 'rules' branch, I'm doing a bit of a cleanup of the existing monolithic Validator class. This might be a good moment to work towards a V2.0, but I would like to drop support for some older PHP-versions:

    Have a look at some of the PHP-versions and their support status

    PHP 5.3 and 5.4 have been out of security support for well over a year, and 5.5 has been unsupported for 6 months. 5.6 is now in security support, but still used by quite a lot of people.

    I think dropping support for 5.3 is a no-brainer. It's ancient by now and dropping it will give us short array syntax. I would drop 5.4 and 5.5 too, but only if I can get whoever ends up running vlucas/spot2 to go along with that. On the other end PHP 7.0 and 7.1 should be supported in the near future (It seems to be working out of the box).

    Is there any good reason why we should keep supporting 5.3, 5.4 and 5.5 that I'm missing? Most of my projects have been at least on 5.6 for quite some time now, but I'm always interested in hearing your part of the story.

    (ps: If you haven't already, be sure to check out PHP 7.+, it's very very good)

    question 
    opened by willemwollebrants 8
  • Make length between greedy and non-greedy

    Make length between greedy and non-greedy

    Should we give the option of length between being optionally non-greedy?

    For instance, length between 5-10 greedy would be 5,6,7,8,9,10

    Non-greedy would be 6,7,8,9

    We could also have low or high greedy, so it'd match 5,6,7,8,9 for low greedy or 6,7,8,9,10 for high greedy

    It would basically involve adding a third parameter, with a value of either 'low', 'high', 'both' or false if we wanted to go the whole hog.

    I wanted to get opinions before I go ahead and create it on whether it would be beneficial, what terminology we should use for 'low greedy' etc if we take that path and also to see if anybody else has an opinion about things like this!

    opened by willishq 8
  • Alternative Rule Syntax?

    Alternative Rule Syntax?

    Instead of the current array-notation syntax:

    $rules = [
        'required' => 'foo',
        'accepted' => 'bar',
        'integer' => 'bar'
    ];
    

    I would prefer to use a syntax like Zend and Laravel have them:

    $rules = [
        'foo' => 'required',
        'bar' => ['accepted', 'integer'],
    ];
    

    Is there any way to accomplish this?

    enhancement 
    opened by Padrio 7
  • compatibility with php8.1

    compatibility with php8.1

    1. changed method used in test to fix below warning 1) ValidateAddInstanceRuleTest::testUniqueRuleName assertRegExp() is deprecated and will be removed in PHPUnit 10. Refactor your code to use assertMatchesRegularExpression() instead.
    2. added early return for case of value being null to fix below warning Deprecated: strtotime(): Passing null to parameter #1 ($datetime) of type string is deprecated
    opened by togishima 0
  • Problem with integer validator

    Problem with integer validator

    Hi, I validate a integer field with the next rules

    $rules = [
        'field-name' => [
            'integer',
            ['min', 1]
        ]
    ];
    
    $data = [
        'field-name' => ''  // Empty string
    ];
    

    but the validations pass without errors, for the error to be detected I had to add the following rules

    $rules = [
        'field-name' => [
            'optional',
            ['required', true],
            'integer',
            ['min', 1]
        ]
    ];
    

    this generates confusing code, and as more fields are added it gets even more confusing

    Note: sorry for my english and thanks for your time.

    opened by demiancy 0
  • Add Sinhala (si) language

    Add Sinhala (si) language

    Adds Sinhala language translations. I'm a native speaker, and more often than not, we use the English terms for popular words even in many government documents, so I continued to use terms like boolean, URL, IP, etc.

    opened by Ayesh 0
Releases(v1.4.11)
  • v1.4.11(Oct 14, 2022)

  • v1.4.10(Jul 8, 2021)

  • v1.4.9(Dec 1, 2020)

  • v1.4.8(Oct 15, 2020)

  • v1.4.7(Aug 29, 2019)

  • v1.4.6(Aug 23, 2019)

  • v1.4.5(Mar 21, 2019)

  • v1.4.4(Dec 14, 2018)

    Fixed a bug[#262] where array elements where considered required when any rule was applied to them New rules for dealing with arrays: subset and containsUnique Languages: new string in Lithuanian, Norwegian Bokmål added Additional documentation and comments

    Source code(tar.gz)
    Source code(zip)
  • v1.4.3(May 6, 2018)

    New languages: Lithuanian, Swedish, Korean New option to stop validating when the first error is encountered Support for nested arrays for 'equals' and 'different' rules Enhanced tests

    Source code(tar.gz)
    Source code(zip)
  • v1.4.2(Oct 31, 2017)

    The validateRequired method required $fields to be an array, and this broke compatibility with objects that implement PHP's ArrayAccess interface.

    Please note that while ArrayAccess-objects will probably work most of the time, Valitron is meant to be used with actual arrays.

    Source code(tar.gz)
    Source code(zip)
  • v1.4.1(Oct 23, 2017)

    • updated translations for pt-br, it and fr
    • less blowing up of php when an array is passed to a rule that expects a string
    • don't add {field} to a custom error message if it already exists
    • added a flag to force the required rule on empty fields
    Source code(tar.gz)
    Source code(zip)
  • v1.4.0(Feb 27, 2017)

    Validator::mapFieldRules() provides another way of adding rules on a per-field basis

    Added a flag to validateInteger() to enable strict checking (bypassing PHP's automatic conversions)

    Source code(tar.gz)
    Source code(zip)
  • v1.3.1(Dec 9, 2016)

    • Fixed a bug where Validator::withData would erase all rules.
    • Added test to make sure Validator::withData actually works as intended
    • Added "Re-use of validation rules" to the readme

    Massive thanks to @wenbinye for spotting the bug, and sorry for any inconvenience it may have caused

    Source code(tar.gz)
    Source code(zip)
  • v1.3.0(Dec 2, 2016)

    General:

    • Validator::rule now supports any kind of callable
    • Validator objects are re-usable for different data

    Languages:

    • Norwegian
    • Slovak

    Rules:

    • New 'between' rule: Validate the value of a field is between min and max values
    • Updated 'contains' rule: case-sensitivity can now be toggled using a parameter (defaults to case-sensitive)

    Thanks to @willemwollebrants for his work on issues and PRs to get this release out.

    Source code(tar.gz)
    Source code(zip)
  • v1.2.5(Mar 16, 2016)

    Updated:

    • validateAccepted() now also accepts string '1' as valid

    New functionality:

    • "optional" rule: Value does not need to be included in data array. If it is however, it must pass validation.
    • callback rules: use custom callbacks or closures

    New languages:

    • Dutch, Turkish, Azerbaijani

    Updated language:

    • Portugese (Brazil)
    Source code(tar.gz)
    Source code(zip)
Owner
Vance Lucas
Co-founder of @techlahoma. Creator of BudgetSheet, Frisby.js, phpdotenv, valitron, and other open-source projects. Engineering Lead/Manager. FT Remote from OKC
Vance Lucas
Lightweight and feature-rich PHP validation and filtering library. Support scene grouping, pre-filtering, array checking, custom validators, custom messages. 轻量且功能丰富的PHP验证、过滤库。支持场景分组,前置过滤,数组检查,自定义验证器,自定义消息。

PHP Validate 一个简洁小巧且功能完善的php验证、过滤库。 简单方便,支持添加自定义验证器 支持前置验证检查, 自定义如何判断非空 支持将规则按场景进行分组设置。或者部分验证 支持在进行验证前对值使用过滤器进行净化过滤内置过滤器 支持在进行验证前置处理和后置处理独立验证处理 支持自定义每

Inhere 246 Jan 5, 2023
[READ-ONLY] Validation library from CakePHP. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Validation Library The validation library in CakePHP provides features to build validators that can validate arbitrary arrays of data with eas

CakePHP 39 Oct 11, 2022
Light and extendable schema validation library

Light PHP validation library For everyone who uses MongoDB or other NoSQL solution and cares about what client sends to his/her database and looking f

Alexander Serkin 43 Sep 28, 2022
An extensible validation library for your data with sane defaults.

Hird Hirds, also known as housecarls, was a gathering of hirdmen, who functioned as the king's personal guards during the viking age and the early mid

Asko Nõmm 13 Apr 23, 2022
FyreValidation is a free, open-source validation library for PHP.

FyreValidation FyreValidation is a free, validation library for PHP. Table Of Contents Installation Validators Rules Error Messages Installation Using

Elusive 0 Jan 15, 2022
File uploads with validation and storage strategies

Upload This component simplifies file validation and uploading. Usage Assume a file is uploaded with this HTML form: <form method="POST" enctype="mult

Brandon Savage 1.7k Dec 27, 2022
Abstracts HTTP request input handling, providing an easy interface for data hydration and validation

Linio Input Linio Input is yet another component of the Linio Framework. It aims to abstract HTTP request input handling, allowing a seamless integrat

Linio 41 Dec 12, 2021
One Line Validation, For CodeIgniter 4

One Line Validation (OLV) is a package made for CodeIgniter 4 to provide a fast and single line validation experience ideal for CDN and/or API services consuming the Validation System from CodeIgniter 4.

AJ Meireles 2 Sep 21, 2021
🔒 Laravel validation rule that checks if a password has been exposed in a data breach.

?? Laravel Password Exposed Validation Rule This package provides a Laravel validation rule that checks if a password has been exposed in a data breac

Jordan Hall 85 Apr 26, 2022
Validation rules for Money and Currency

money-validation-laravel Validation rules for Money and Currency Installation composer require brokeyourbike/money-validation-laravel Usage Package us

Ivan Stasiuk 1 Oct 25, 2021
高性能的验证器组件(Validation),适用于 Hyperf 或 Laravel 框架,可获得数百倍的性能提升

验证器 简介 兼容 Hyperf/Laravel Validation 规则 部分场景可获得约 500 倍性能提升 验证器可多次复用不同数据,无状态设计 规则可全局复用 智能合并验证规则 安装 环境要求 PHP >= 8.0 mbstring 扩展 ctype 扩展 安装命令 composer re

KK集团 80 Dec 9, 2022
Extension for the Laravel validation class

Intervention Validation Intervention Validation is an extension library for Laravel's own validation system. The package adds rules to validate data l

null 370 Dec 30, 2022
Extra validation rules for dealing with images in Laravel 5.

Image-Validator Extra validation rules for dealing with images in Laravel 5. NOTE: As of Laravel version 5.2, there are now built-in validation rules

Colin Viebrock 223 Jun 16, 2022
laminas-password-validator provides a validator for character-set based input validation.

laminas-password-validator laminas-password-validator provides a validator for character-set based input validation. Installation composer require pra

null 1 Mar 8, 2022
Laravel Validation Service

Laravel Validation Service Installation Add "prettus/laravel-repository": "1.1.*" to composer.json "prettus/laravel-validation": "1.1.*" Create a vali

Anderson Andrade 398 Nov 25, 2022
🔒 Laravel validation rule that checks if a password has been exposed in a data breach.

?? Laravel Password Exposed Validation Rule This package provides a Laravel validation rule that checks if a password has been exposed in a data breac

Jordan Hall 85 Apr 26, 2022
A simple filtering library for PHP

Filterus - A flexible PHP 5.3 filter package Filter Methods: Each filter class has two primary methods: $filter->filter($var) - returns a modified ver

Anthony Ferrara 451 Dec 27, 2022
PHP library - Validators for standards from ISO, International Finance, Public Administrations, GS1, Manufacturing Industry, Phone numbers & Zipcodes for many countries

IsoCodes PHP library - Validators for standards from ISO, International Finance, Public Administrations, GS1, Book Industry, Phone numbers & Zipcodes

Ronan Guilloux 767 Jan 2, 2023
Library that offers Input Filtering based on Annotations for use with Objects. Check out 2.dev for 2.0 pre-release.

DMS Filter Component This library provides a service that can be used to filter object values based on annotations Install Use composer to add DMS\Fil

Rafael Dohms 89 Nov 28, 2022