Code Monkey home page Code Monkey logo

valitron's Introduction

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.

valitron's People

Contributors

auroraeosrose avatar brandonlamb avatar diegosala avatar ecoreng avatar euantorano avatar fdipilla avatar hided62 avatar hiroy avatar jabarihunt avatar jatubio avatar joelclermont avatar justinhook avatar laverboy avatar majerle avatar mangopeaches avatar matt3o12 avatar misantron avatar neves avatar notona avatar peter-kinamo avatar peter279k avatar rayne avatar realjay007 avatar soulcanada avatar vandarin avatar veganista avatar vlucas avatar willemwollebrants avatar willry avatar zonuexe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

valitron's Issues

Default values for non-required fields

Still working on the client-side interface, but in the meantime I've come up with something that others might find useful. Basically, the purpose is to allow default values for non-required fields. So, if a $_GET or $_POST array is passed into valitron, it can be easily updated with default values for missing parameters.

Extra function in valitron:

    public function setDefault($field, $defaultValue) {
        if (!isset($this->_fields[$field])){
            $this->_fields[$field] = $defaultValue;
        }
        return true;
    }

Usage:

// Sanitize input data
$get = filter_input_array(INPUT_GET, FILTER_SANITIZE_SPECIAL_CHARS);

// Initialize validation
$v = new Valitron\Validator($get);

// Required fields
$v->rule('required', 'box_id');

// Optional fields with default values
$v->setDefault('title', 'Cool Dude');
$v->setDefault('limit', null);

// Validate!
$v->validate();

// Handle errors
if (count($v->errors()) > 0)
    exit();

// Update input array with any new default values
$get = $v->data();

Note for rule accepted

While working with php frameworks I came across one small problem which could help others.

Laravel, slim... are returning NULL for checkbox input type in state when checkbox is not accepted .

Because of that checkbox won't be run against validation. Simple fix is to set checkbox value to 'off' instead of NULL.

Set the checkAndSetLabel() as protected

Is it possible to set the checkAndSetLabel() as protected?
When I want to extend the class with custom error() function cannot because the checkAndSetLabel() is private.
Thanks.

need interface for field name in error messages

I suggest that field name in error messages should come from displayed field name.

And I think Valitron should provide interface for manipulating field name in error messages.

Currently field names are generated from key of input array in Validator constructor.
However this behavior is very nasty when the message should be non-English, which requires extraneous str_replaces for all field names.

All suggestion are welcomed.

Thank you.

Add credit card validation

Recently I was working on a project and I needed to validate a credit card was valid, so I created a new basic filter for Valitron and it worked ok.

I was going to work on an improved filter for it (more verbose) but before I do I wondered if it is something you would consider implementing into the core?

My original code checked only if a card was valid but a more verbose system would optionally filter by card type and suchlike.

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?

Dealing with "pseudo-optional" form fields

I love the concept of this project, and I'm looking to integrate this with one of my current projects (https://github.com/alexweissman/UserFrosting). Right now, our validation rules are hardcoded, repetitive if-else statements all over our codebase. This would help clean it up nicely.

I was wondering, do you have any recommendations for how to deal with "pseudo-optional" HTML form fields such as checkboxes? I.e., fields which aren't really "optional", but whose absence is interpreted as false and presence as true? Right now we're using the isset function, but I wonder if there is a more elegant way using Valitron.

Possible problem with message field position in message

This is part of code in rule methode

$this->_validations[] = array(
            'rule' => $rule,
            'fields' => (array) $fields,
            'params' => (array) $params,
            'message' => '{field} ' . $message
        );
        return $this;

If we define in language file rule like this ''required' => "Field {field} is required" it will output

"Email Field Email is required"

I know that i can do some thing like this:

$v->rule('required', array('name', 'email'))->message('{field} is required')->label('Name');

But adding this in multiple places and than, for example, client want me to change message can be pain in ass.

Am I missing something?

Labels not working correctly?

I'm having some trouble getting the labels to perform correctly. Valitron continues to use the actual HTML field name (i.e. passwordConfirm) in the display to users instead of the label I am trying to apply: "Password Confirmation." Here's some sample code:

$v->rule('required', ['firstName', 'lastName', 'email', 'phone1', 'phone2', 'phone3', 'password', 'passwordConfirm', 'terms', 'companyCode']);
    $v->rule('email', 'email');
    $v->rule('integer', ['phone1', 'phone2', 'phone3']);
    $v->rule('accepted', 'terms');
    $v->rule('length', 'phone1', 3);
    $v->rule('length', 'phone2', 3);
    $v->rule('length', 'phone3', 4);
    $v->rule('equals', 'password', 'passwordConfirm');

    $v->labels(array(
        'firstName' => 'First name',
        'lastName' => 'Last name',
        'email' => 'Email address',
        'phone1' => 'Area Code',
        'phone2' => 'Phone Number',
        'phone3' => 'Phone Number',
        'password' => 'Password',
        'passwordConfirm' => 'Password',
        'terms' => 'Terms and Conditions',
        'companyCode' => 'Employer Company Code'
    ));

Additionally, here is the en.php file in the languages folder:

<?php
return array(
    'required' => "Required",
    'equals' => "Must be the same as '%s'",
    'different' => "Must be different than '%s'",
    'accepted' => "Must be accepted",
    'numeric' => "Must be numeric",
    'integer' => "Must be an integer (0-9)",
    'length' => "Must be longer than %d",
    'min' => "Must be greater than %s",
    'max' => "Must be less than %s",
    'in' => "Invalid value",
    'notIn' => "Invalid value",
    'ip' => "Invalid IP address",
    'email' => "Invalid email address",
    'url' => "Invalid URL",
    'urlActive' => "Must be active domain",
    'alpha' => "Must contain only letters a-z",
    'alphaNum' => "Must contain only letters a-z and/or numbers 0-9",
    'slug' => "Must contain only letters a-z, numbers 0-9, dashes and underscores",
    'regex' => "Invalid format",
    'date' => "Invalid date",
    'dateFormat' => "Must be date with format '%s'",
    'dateBefore' => "Must be date before '%s'",
    'dateAfter' => "Must be date after '%s'",
    'contains' => "Must contain %s"
);
?>

Validate combination of fields, one should be filled (different)

Given:

$v = new \Valitron\Validator(array('foo' => '', 'bar' => '')); 
$v->rule('different', 'foo', 'bar');
$v->validate(); // true

That doesn't seem correct to me; foo and bar are not different at all. In my case either foo or bar should be filled, but if both are empty, validation should fail.

I guess this is caused by #14. I can't require both fields; as foo is only required when bar is empty, and vice versa.

_validations not associative

The keys of the array "_validations" aren't a name of a validation method.

Check function "hasRule": [https://github.com/vlucas/valitron/blob/master/src/Valitron/Validator.php#L533].
As the _validations array has a numeric index, this function will always return FALSE when being called from validate().

Field messages on alternate syntax for adding rules

Hello,

Is there a way to add custom messages when adding rules with the alternate syntax.
Like in this example, where to add custom messages?

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

Thanks,

Grabbing individual errors

Thanks for giving me an alternative to that awkward Respect/Validator thing.

I know there is a function errors() in the Valitron library, can someone add a function to allow retrieval of the error string that represents one particular field.

I realise I can just do $v->errors() and get the index of the array. However I think it's cleaner for future dev to have a function that retrieves it to save breaking changes later on if you ever change the format of the errors. Even if that function is simply indexing the array for the time being.

Cheers.

Add example to docs of custom rule comparing two supplied pieces of data?

Hi all:

Would it be possible to add an example of a custom rule to the README that shows how to compare two items of supplied data, in the same way as the already-defined equals and different rules do? Even something simple like a lessThan or greaterThan rule would be great to illustrate how that would work.

Thanks :)

RequiredWith

Title says it all.

How would you implement this?

[Suggestion] Old input

Title says it all.

It is not hard to do it manually but including old input with errors would be a nice feature.

Field Label

It would be good to add field label when defining rules rather than the code trying to work out what the label should be based on the field name.

Currently I have a password confirm field and the label is Password Confirm but the output from validation is. I want to be able to define this.

$v->rule('required', array('first_name', 'last_name', 'email_address', 'dob'));
$v->label(array(
    'first_name' => 'First Name',
    'last_name' => 'Last Name',
    'email_address' => 'Email',
    'dob' => 'Date of Birth',
));

Something like this would be useful, because I could define all my field labels globally. I have this working on my current setup but I find my solution a bit hacky, when I work out a cleaner solution I will send a PR.

Add rules in bulk

Would you accept a PR to add rules in bulk? To keep it simple, the method would accept an array of arrays. Each internal array would be the same values you would have passed to the rule() method individually.

I'd propose naming the method setRules() or perhaps even just rules().

$rules = array(
    array('required', 'name'),
    array('length', 'name', 14)
);
$v = new Validator(array('name' => 'Chester Tester'));
$v->rules($rules);
$v->validate();

If we wanted to get a little more clever, perhaps we could use a slightly more complex structure, allowing for a more readable rules array:

$rules = array(
    'required' => 'name',
    'length'   => array(
        array('name', 14),
        array('gender', 1)
    )
);
$v = new Validator(array('name' => 'Chester Tester', 'gender' => 'M'));
$v->rules($rules);
$v->validate();

In this format, the top level array is just keys/values where the key is a rule type and the val is either a single param, array of params or array of arrays. An array of params would allow for rules that require an array of params. The array of arrays would allow you to specify multiple rules of a single type (like my length example).

The second structure would look really nice with array literals in 5.4.

I'm also not quite sure how to write an effective unit test for this since $_validators is protected. Ideas?

Validation for length - Message is incorrect for between cases

Assuming the following validation rule stipulating that the firstname and lastname fields should be between 2 and 25 characters in length:

'length' => [['firstname', 2, 25], ['lastname', 2, 25]],

The language file supplies the following error message regardless:

'length' => "must be longer than %d",

a better solution would be to have a between for text lengths:

'between' => "must be between %d and %d characters",

Allow re-use of validation rules and storage

Requiring to set the data in the constructor is an odd choice that removes the ability to validate several values with the same rules (user has to config a new object each time). Simple fix: add setData().

As it is, storing data in the object makes this not a validator but a sort of validating-container hybrid; I can't just serialize this and store it somewhere without also storing the data.

Moving the static state to object state would also help there.

Alpha validation with accented characters?

Hey!
I'm just wondering -- I don't really know if there's something I'm missing or if it's a bug, but there seems to be problems when trying to validate alpha/alphanumeric strings that contain accented characters.

require 'lib/Valitron/Validator.php';
use Valitron\Validator as Validator;
$arr = [
    "last_name" => "áéíñ"
];
$v = new Validator($arr);
$v->rule('alpha','last_name');
$v->validate();
var_dump($v->errors()); // prints array(1) { ["last_name"]=> array(1) { [0]=> string(39) "Last Name must contain only letters a-z" } }

Any ideas or anyhing that needs to be set up before using Valitron?

Thanks!

validate phrase

Hi,
there is possibility to validate string with spaces, accents, etc like "hello it's my message... XD".
I thinks it's possible if you use is_string() php function.
It's possible to add this function? :)

thanks
Leo

Interface with client-side validation plugins

In modern web applications, is important to validate form data on both the server-side (for security) and the client-side (for usability). Valitron does the server-side validation quite nicely, and there are some very good client-side validation plugins out there, such as bootstrapvalidator.

However, every time one builds or modifies a form, one must add the appropriate rules to both the server- and client-side code. A really useful feature would be if Valitron could generate the appropriate client-side rules (in JSON, for example) automatically. The client could then fetch these rules from Valitron either when they load the form, or through a separate AJAX request.

Problem in validateDateFormat

The issue happens when you try to validate a date in pt-br format (d/m/Y). I changed the return in method validateDateFormat to: return $parsed['warning_count'] === 0;

Length error output error

$rules = array(
'length' => array(array('input1', 6),array('input2', 10)),
);

this rule gives following error when:
input1 = 'abcdefghdkjfakjdkjkf'

[1] => Input1 must be longer than 6

I think it should output folowing error:
[1] => Input1 must be exactly 6 digits.

Bug using array notation and required

Adopted one of the examples to my needs and came across a possible bug:

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

Output:

Array ( [settings.threshold] => Array ( [0] => Settings.threshold is required ) )

Running the same code but with this validator:

$v->rule('lengthMin', 'settings.threshold',1);

produces the expected output:

Yay! We're all good!

Min doesn't appear to work correctly with zero

If min is set to 1 then 0 still passes as a valid value:

php > $v = new Valitron\Validator(array('name' => 0));
php > $v->rule('min', 'name', 1);
php > var_dump($v->validate());
bool(true)

This doesn't appear to be the case if the value is non-zero:

php > $v = new Valitron\Validator(array('name' => 1));
php > $v->rule('min', 'name', 2);
php > var_dump($v->validate());
bool(false)

Implement JSON Schema validation

So for a while, I've been thinking about how validation plugins for different languages/platforms each have their own particular "language" for specifying validation rules and parameters. For example, FormValidation has the greaterThan validator, while Valitron has the min rule, Symfony2 has the GreaterThan constraint, Djanjo has MinValueValidator, etc.

The lack of a standard for validation rules is a problem, because it limits interoperability between client- and server-side code, as well as among different client- and server-side languages/frameworks/plugins.

I was going to try to develop my own standard, but I found out there is already an effort called JSON Schema. Would you consider extending Valitron to be able to load validation rules from a schema in this format?

Array validation!

I am validating an array like so:

    $v->rule('numeric', array('grades.*'));
    $v->rule('min', array('grades.*'), 0);
    $v->rule('max', array('grades.*'), 10);

However in case of validation failure i can't find a way to get the index of the specific field that failed validation as $v->errors() returns something like the following:

Array ( [grades.*] => Array ( [0] => Grades.* mplah mpah mplah validation error ) )

Am i missing something here? Or is it a valitron's shortcoming?

construction

Hi,

At the moment the constructor takes a single $data argument and the other arguments are optional. Is it not a better solution to have the constructor take a single optional argument of type array that holds all the necessary/optional construction data for easier integration into existing systems?

__construct($params = array())

Custom validation rules and access to other fields values

Sometimes when you want to validate a field first you need to look at another field, second. That's the case when you are comparing two password fields for instance, and for that you would use the builting equals validator. But what if you need such functionality in a custom validation rule that you add using the static method addRule()? At the moment it is not possible.

Perhaps it would be possible to pass a read-only version of the protected $_fields property of Validator to the callback used in addRule().

Of course this is a non-issue if one is okay with just extending the Validator class and adding validation methods to it.

Custom Messages For Rules Set By Alternative Syntax

I don't see a way to set the custom messages for rules set by:

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

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

Am I missing something?

could add:
public function messages($msgs)
{
static::$_ruleMessages = array_merge(static::$_ruleMessages, $msgs);
return $this;
}

But that has to be run before the rules have been set

lengthMin (and probably lengthMax) inappropriate validation error message

While lengthMin rule sets the minimum ALLOWED length of the string the validation error that is triggered is as follows:

"lengthMin"     => "must contain greater than %d characters",

instead of something that includes the minimum value like

"lengthMin"     => "must contain equal to or greater than %d characters",

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;

Add separate class for validators

Now all validators are stored together with the logic of the library in the one class.
In my opinion it is not very pretty. It would be logical to put validators into a separate class.
And while creating instance of the Valitron, we inject validators class into Valitron via constructor.

For example:

class Validator
{

    public function __construct($v = null, ect...)
    {
        $this->validators = $v === null ? new Validators : $v;
        // ....
    }

}

class Validators 
{

    public function length($args ...)
    {
        // ...
        return $result
    }

    // ...

}

This also allows to put my own class, which contains my set of the validators.

wrong integer validation

Hello when I validate a filed as beeing integer, I'm expecting to return false in case it's "123" because internally this is a string.

Instead using return filter_var($value, \FILTER_VALIDATE_INT) !== false; I think better to use is_int .

Docs should be updated for lengthBetween

There is no more lengthBetween. According to the code one just adds another parameter to length for lengthBetween functionality. This is confusing as the README still lists lengthBetween but if you try lengthBetween it'll throw an addRule error.

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!

Language typo

In English language file:
'regex' => "contains invalid chatacters",

it's chaRacters 😄

Length rule

->rule('length', 'phone', 12]);

The phone have to be 12 longer but on message you say "must be longer than 12".

Is this right?

Composer version

Please remove the version property from the composer.json file, since when this is forgotten we still have 1.1.7 when current latest release is 1.1.8. Let packagist manage the version based on tags instead of looking for the version property in the composer.json.

Regarding the in_array() commit.

I am talking about the changes in this commit.
#114

Though I have added an argument for the strict flag, It just doesn't seem to work and always defaults to false no matter what I pass it.

Since I do not have a lot of time I just reverted the changes and just created a clone function with everything similar with the strict flag added, and named it "validateIns" as compared to original "validateIn".

eg.
$v->rule('ins', 'xyz', array('0', '1'));

And this is working fine for me.
But if you could make it better( as to why and how my suggested commit isn't working) I'd be glad.
If I get some time I myself shall try fixing it.

Thanks for your immense contribution.
This library is exactly that worked for me, since most of my applications are a bit complex and not quiet easy with other libraries like GUMP.

construct validation rules before supplying data

At the moment, Valitron has to be initialized with an array of field->value mappings. So, there is no way to add data to be validated after initialization. Any thoughts on adding a setData method?

Accepted Rule

There is a little Problem with the "accepted"-Rule. If i wan't that the accepted rule work, i have to set to the field also the "required"-rule. The Problem is that in the function Validate a field have not to be empty, except the field has a "required"-rule.

I have change your code at line 752,

if (($v['rule'] !== 'required' && !$this->hasRule('required', $field) && (!isset($value) || $value === '')) && !$this->hasRule('accepted', $field)) {
  continue;
}

Language definition for length validation

Length validation returns "must be longer.." even if the value is shorter. Sorry I don't have the time to add a pull request, here's my fix:

Replaced
'length' => "must be longer than %d",
with
'length' => "length must be between %d and %d",

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.