### Install Valitron with Composer Source: https://github.com/vlucas/valitron/blob/master/README.md Use Composer to install Valitron. This command adds the library as a dependency to your project. ```bash curl -s http://getcomposer.org/installer | php php composer.phar require vlucas/valitron ``` -------------------------------- ### Setting Global Language and Language Directory Source: https://github.com/vlucas/valitron/blob/master/README.md Provides an example of how to set the language and language directory globally for Valitron. Ensure `langDir` is set before `lang`. ```php // boot or config file use Valitron\Validator as V; V::langDir(__DIR__.'/validator_lang'); // always set langDir before lang. V::lang('ar'); ``` -------------------------------- ### Basic Validation Example Source: https://github.com/vlucas/valitron/blob/master/README.md Demonstrates basic validation of a single field. Initialize Valitron with data, apply a 'required' rule to a field, and check validation status. ```php $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()); } ``` -------------------------------- ### Run Validation and Get Errors Source: https://context7.com/vlucas/valitron/llms.txt Executes all registered rules and returns true if every rule passes, false otherwise. Iterates through errors if validation fails. ```php $v = new Validator(['score' => 'not-a-number']); $v->rule('required', 'score')->rule('numeric', 'score')->rule('min', 'score', 0); if ($v->validate()) { echo "Score is valid."; } else { foreach ($v->errors() as $field => $messages) { foreach ($messages as $msg) { echo "$field: $msg\n"; } } // score: Score must be numeric } ``` -------------------------------- ### Conditional Validation Rules Source: https://github.com/vlucas/valitron/blob/master/README.md Illustrates using conditional validation rules like `requiredWithout` and `requiredWith`. This example sets up rules for authentication, requiring either a token or a password based on the presence of other fields. ```php // this rule set would work for either data set... $data = ['email' => 'test@test.com', 'password' => 'mypassword']; // or... $data = ['token' => 'jashdjahs83rufh89y38h38h']; $v = new Valitron\Validator($data); $v->rules([ 'requiredWithout' => [ ['token', ['email', 'password'], true] ], 'requiredWith' => [ ['password', ['email']] ], 'email' => [ ['email'] ] 'optional' => [ ['email'] ] ]); $this->assertTrue($v->validate()); ``` -------------------------------- ### 'requiredWith' rule with multiple dependencies Source: https://github.com/vlucas/valitron/blob/master/README.md This 'requiredWith' rule example demonstrates how to make a field required if ANY of the specified fields ('username' or 'email') are present and not empty. Pass an array of field names as the third parameter. ```php $v->rule('requiredWith', 'password', ['username', 'email']); ``` -------------------------------- ### Validating Numeric Array Members with Dot Syntax Source: https://github.com/vlucas/valitron/blob/master/README.md Demonstrates using dot syntax with an asterisk to validate all members of a simple numeric array. This example ensures all values in the 'values' array are less than or equal to 100. ```php $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()); } ``` -------------------------------- ### Accessing Nested Values with Dot Notation Source: https://github.com/vlucas/valitron/blob/master/README.md Shows how to access deeply nested values within an array using dot notation. This example applies 'alpha' and 'alphaNum' rules to specific user profile fields. ```php $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()); } ``` -------------------------------- ### Validate Regex Pattern Source: https://github.com/vlucas/valitron/blob/master/README.md The 'regex' rule checks if a field matches a provided regular expression pattern. This example checks for 5-10 alphanumeric characters. ```php $v->rule('regex', 'username', '/^[a-zA-Z0-9]{5,10}$/'); ``` ```php $v = new Valitron\Validator(['username' => 'Batman123']); $v->rules([ 'regex' => [ ['username', '/^[a-zA-Z0-9]{5,10}$/'] ] ]); $v->validate(); ``` -------------------------------- ### Validating Nested Array Members with Dot Syntax Source: https://github.com/vlucas/valitron/blob/master/README.md Illustrates using dot syntax with an asterisk to validate each member of a nested array. This example validates the 'threshold' within each item of the 'settings' array. ```php $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()); } ``` -------------------------------- ### Validate Instance of a Class Source: https://github.com/vlucas/valitron/blob/master/README.md Checks if a field's value is an instance of a specified class or a given object. Examples show validation against a class name string and against an existing object. ```php $v->rule('instanceOf', 'date', \DateTime); ``` ```php $v = new Valitron\Validator(['date' => new \DateTime()]); $v->rules([ 'instanceOf' => [ ['date', 'DateTime'] ] ]); $v->validate(); ``` ```php $v = new Valitron\Validator(['date' => new \DateTime()]); $existingDateObject = new \DateTime(); $v->rules([ 'instanceOf' => [ ['date', $existingDateObject] ] ]); $v->validate(); ``` -------------------------------- ### Retrieve Validation Errors Source: https://context7.com/vlucas/valitron/llms.txt Get all validation errors as a nested array or errors for a specific field. Returns false if the field has no errors or was not validated. ```php $v = new Validator(['age' => 'abc', 'email' => 'not-valid']); $v->rule('integer', 'age')->rule('email', 'email'); $v->validate(); // All errors $all = $v->errors(); // ['age' => ['Age must be a valid integer'], 'email' => ['Email is not a valid email address']] // Single field errors $ageErrors = $v->errors('age'); // ['Age must be a valid integer'] $noErrors = $v->errors('name'); // false — field was not validated ``` -------------------------------- ### Disabling Field Name Prepending in Error Messages Source: https://github.com/vlucas/valitron/blob/master/README.md Demonstrates how to disable the prepending of field names in error messages for cleaner output. The example shows the difference in error output with and without prepended labels. ```php 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" ] ] ``` -------------------------------- ### requiredWithout strict mode validation example Source: https://github.com/vlucas/valitron/blob/master/README.md In strict mode, validate() returns true if all fields are provided, as the username field is not required. Use when the username should not be required if first_name and last_name are both present. ```php $v = new Valitron\Validator(['first_name' => 'steve', 'last_name' => 'holt']); $v->rules([ 'requiredWithout' => [ ['suffix', ['first_name', 'last_name'], true] ] ]); $v->validate(); ``` -------------------------------- ### Check for Unique Array Elements Source: https://github.com/vlucas/valitron/blob/master/README.md Validates that all elements within an array field are unique. The provided examples show a valid case and a case with duplicate values. ```php $v->rule('containsUnique', 'colors'); ``` ```php $v = new Valitron\Validator(['colors' => ['purple', 'blue']]); $v->rules([ 'containsUnique' => [ ['colors'] ] ]); $v->validate(); ``` ```php $v = new Valitron\Validator(['colors' => ['purple', 'purple']]); $v->rules([ 'containsUnique' => [ ['colors'] ] ]); $v->validate(); ``` -------------------------------- ### requiredWith strict mode validation example Source: https://github.com/vlucas/valitron/blob/master/README.md In strict mode, validate() returns true if not all fields are provided, as the suffix field is not required. Use when the suffix field should not be required if first_name or last_name are missing. ```php $v = new Valitron\Validator(['first_name' => 'steve']); $v->rules([ 'requiredWith' => [ ['suffix', ['first_name', 'last_name'], true] ] ]); $v->validate(); ``` -------------------------------- ### Validate Array Subset Source: https://github.com/vlucas/valitron/blob/master/README.md Ensures all values in a field (scalar or array) are present within a given set of allowed values. The provided example demonstrates a case where a value is not found in the allowed set. ```php $v->rule('subset', 'colors', ['green', 'blue', 'orange']); ``` ```php $v = new Valitron\Validator(['colors' => ['green', 'blue']]); $v->rules([ 'subset' => [ ['colors', ['orange', 'green', 'blue', 'red']] ] ]); $v->validate(); ``` ```php $v = new Valitron\Validator(['colors' => ['purple', 'blue']]); $v->rules([ 'subset' => [ ['colors', ['orange', 'green', 'blue', 'red']] ] ]); $v->validate(); ``` -------------------------------- ### Alternate syntax for different rule Source: https://github.com/vlucas/valitron/blob/master/README.md Demonstrates the alternate syntax for the different rule, where username and password fields are set and validated to be different. ```php $v = new Valitron\Validator(['username' => 'spiderman', 'password' => 'Gr33nG0Blin']); $v->rules([ 'different' => [ ['username', 'password'] ] ]); $v->validate(); ``` -------------------------------- ### Alternate syntax for equals rule Source: https://github.com/vlucas/valitron/blob/master/README.md Demonstrates the alternate syntax for the equals rule, where password and confirmPassword fields are set and validated for equality. ```php $v = new Valitron\Validator(['password' => 'youshouldnotseethis', 'confirmPassword' => 'youshouldnotseethis']); $v->rules([ 'equals' => [ ['password', 'confirmPassword'] ] ]); $v->validate(); ``` -------------------------------- ### Alternate syntax for accepted rule Source: https://github.com/vlucas/valitron/blob/master/README.md Demonstrates the alternate syntax for the accepted rule, where the remember_me field is set to true and validated. ```php $v = new Valitron\Validator(['remember_me' => true]); $v->rules([ 'accepted' => [ ['remember_me'] ] ]); $v->validate(); ``` -------------------------------- ### Instantiate Validator with Data Source: https://context7.com/vlucas/valitron/llms.txt Basic instantiation with POST data. Optionally restrict fields or set language globally before instantiation. ```php use Valitron\Validator; // Basic instantiation with POST data $v = new Validator($_POST); // Restrict to known fields only (filters out unexpected keys) $v = new Validator($_POST, ['name', 'email', 'age']); // Set language globally before instantiation Validator::langDir(__DIR__ . '/custom_lang'); Validator::lang('fr'); $v = new Validator(['name' => 'Jean']); ``` -------------------------------- ### Use equals rule Source: https://github.com/vlucas/valitron/blob/master/README.md Checks if two fields are equal and the second field is not null. Use when password and confirmPassword fields must match. ```php $v->rule('equals', 'password', 'confirmPassword'); ``` -------------------------------- ### Alternate syntax for requiredWithout rule Source: https://github.com/vlucas/valitron/blob/master/README.md Demonstrates the alternate syntax for the requiredWithout rule. This passes validation because the username is provided when first_name is not. ```php $v = new Valitron\Validator(['username' => 'spiderman']); $v->rules([ 'requiredWithout' => [ ['username', 'first_name'] ] ]); $v->validate(); ``` -------------------------------- ### Alternate syntax for numeric rule Source: https://github.com/vlucas/valitron/blob/master/README.md Demonstrates the alternate syntax for the numeric rule, where the amount field is set to a float and validated. ```php $v = new Valitron\Validator(['amount' => 3.14]); $v->rules([ 'numeric' => [ ['amount'] ] ]); $v->validate(); ``` -------------------------------- ### Specify Multiple Rules per Rule Type Source: https://github.com/vlucas/valitron/blob/master/README.md Define multiple instances of the same rule type for different fields or with different parameters by creating an array of rule configurations. ```php $rules = [ 'length' => [ ['foo', 5], ['bar', 5] ] ]; ``` -------------------------------- ### Validating POST Data with Multiple Rules Source: https://github.com/vlucas/valitron/blob/master/README.md Shows how to validate data directly from `$_POST` and apply multiple rules to an array of fields. Ensure 'name' is required and 'email' is a valid email format. ```php $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()); } ``` -------------------------------- ### Add Individual Rules After Batch Definition Source: https://github.com/vlucas/valitron/blob/master/README.md Combine batch rule definition using `rules` with individual rule additions using `rule`, useful for custom rules. ```php $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(); ``` -------------------------------- ### setPrependLabels(bool) Source: https://context7.com/vlucas/valitron/llms.txt Control whether field names or labels are prepended to error messages. Setting this to `false` omits the prefix. ```APIDOC ## `setPrependLabels(bool)` — Control Label Prepending When set to `false`, field names/labels are omitted from the beginning of error messages. ```php $v = new Validator(['name' => '']); $v->rule('required', 'name'); $v->setPrependLabels(false); $v->validate(); print_r($v->errors()); // ['name' => ['is required']] (no "Name" prefix) ``` ``` -------------------------------- ### Use accepted rule Source: https://github.com/vlucas/valitron/blob/master/README.md Checks if the field is either 'yes', 'on', 1, or true. Use for boolean or confirmation fields. ```php $v->rule('accepted', 'remember_me'); ``` -------------------------------- ### Run Validation Source: https://context7.com/vlucas/valitron/llms.txt Executes all the rules that have been registered with the validator. It returns `true` if all rules pass validation, and `false` otherwise. ```APIDOC ## `validate()` — Run Validation Executes all registered rules and returns `true` if every rule passes, `false` otherwise. ```php $v = new Validator(['score' => 'not-a-number']); $v->rule('required', 'score')->rule('numeric', 'score')->rule('min', 'score', 0); if ($v->validate()) { echo "Score is valid."; } else { foreach ($v->errors() as $field => $messages) { foreach ($messages as $msg) { echo "$field: $msg\n"; } } // score: Score must be numeric } ``` ``` -------------------------------- ### withData(array $data) Source: https://context7.com/vlucas/valitron/llms.txt Clones the validator instance with a new dataset, retaining all registered rules and configurations. Useful for re-validating with different data. ```APIDOC ## `withData(array $data)` — Re-use Rules with New Data Clones the validator with a fresh data set and cleared errors, keeping all registered rules intact. ```php $v = new Validator([]); $v->rule('required', ['username', 'email']) ->rule('email', 'email') ->rule('lengthMin', 'username', 3); // First dataset — fails $v->validate(); // false // Reuse with valid data $v2 = $v->withData(['username' => 'clark', 'email' => 'clark@daily.com']); $v2->validate(); // true // Reuse with another invalid dataset $v3 = $v->withData(['username' => 'x', 'email' => 'not-email']); $v3->validate(); // false print_r($v3->errors()); ``` ``` -------------------------------- ### Chain Multiple Rules in Valitron Source: https://github.com/vlucas/valitron/blob/master/README.md Apply multiple validation rules sequentially to a field by chaining `rule` method calls. ```php $v = new Valitron\Validator(['email_address' => 'test@test.com']); $v->rule('required', 'email_address')->rule('email', 'email_address'); $v->validate(); ``` -------------------------------- ### Use different rule Source: https://github.com/vlucas/valitron/blob/master/README.md Checks if two fields are different and the second field is not null. Use when username and password fields must not be the same. ```php $v->rule('different', 'username', 'password'); ``` -------------------------------- ### Use Human-Readable Field Labels Source: https://context7.com/vlucas/valitron/llms.txt Replace machine-readable field names with human-readable labels in error output using `label()` or `labels()`. ```php $v = new Validator(['usr_nm' => '', 'usr_email' => 'bad']); $v->rule('required', 'usr_nm')->label('Username'); $v->rule('required', ['usr_nm', 'usr_email']) ->rule('email', 'usr_email'); $v->labels(['usr_nm' => 'Username', 'usr_email' => 'Email Address']); $v->validate(); print_r($v->errors()); // ['usr_nm' => ['Username is required'], // 'usr_email' => ['Email Address is not a valid email address']] ``` -------------------------------- ### Optional Field Validation with Alternate Syntax Source: https://github.com/vlucas/valitron/blob/master/README.md Demonstrates using 'optional' with other rules. If the field is present, it must pass all associated rules (e.g., 'alpha'). If absent, it's considered valid. ```php $v = new Valitron\Validator(['username' => 'batman']); $v->rules([ 'alpha' => [ ['username'] ], 'optional' => [ ['username'] ] ]); $v->validate(); ``` ```php $v = new Valitron\Validator(['username' => 'batman123']); $v->rules([ 'alpha' => [ ['username'] ], 'optional' => [ ['username'] ] ]); $v->validate(); ``` -------------------------------- ### Halt Validation After First Failure Source: https://context7.com/vlucas/valitron/llms.txt Enable `stopOnFirstFail(true)` to stop validation as soon as the first rule fails, resulting in at most one error per field. ```php $v = new Validator(['age' => 'abc']); $v->stopOnFirstFail(true); $v->rule('required', 'age') ->rule('integer', 'age') ->rule('min', 'age', 18); $v->validate(); print_r($v->errors()); // Only one error: ['age' => ['Age must be a valid integer']] ``` -------------------------------- ### Re-use Validation Rules with New Data Source: https://github.com/vlucas/valitron/blob/master/README.md The `withData` method allows you to reuse existing validation rules with a new dataset. This is efficient for validating different data against the same set of rules. ```php $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 ``` -------------------------------- ### Validator Constructor Source: https://context7.com/vlucas/valitron/llms.txt Instantiates a new Validator object. You can provide the data to validate, optionally restrict the fields to consider, and configure the language for error messages. ```APIDOC ## `new Validator($data, $fields, $lang, $langDir)` — Constructor Instantiates a new validator with the data to validate. Optionally restricts which fields are considered (`$fields`), and configures the error-message language. ```php use Valitron\Validator; // Basic instantiation with POST data $v = new Validator($_POST); // Restrict to known fields only (filters out unexpected keys) $v = new Validator($_POST, ['name', 'email', 'age']); // Set language globally before instantiation Validator::langDir(__DIR__ . '/custom_lang'); Validator::lang('fr'); $v = new Validator(['name' => 'Jean']); ``` ``` -------------------------------- ### Reuse Rules with New Data Source: https://context7.com/vlucas/valitron/llms.txt Clone a validator instance with a fresh dataset and cleared errors, retaining all registered rules, using `withData()`. ```php $v = new Validator([]); $v->rule('required', ['username', 'email']) ->rule('email', 'email') ->rule('lengthMin', 'username', 3); // First dataset — fails $v->validate(); // false // Reuse with valid data $v2 = $v->withData(['username' => 'clark', 'email' => 'clark@daily.com']); $v2->validate(); // true // Reuse with another invalid dataset $v3 = $v->withData(['username' => 'x', 'email' => 'not-email']); $v3->validate(); // false print_r($v3->errors()); ``` -------------------------------- ### Add Multiple Rules at Once Source: https://context7.com/vlucas/valitron/llms.txt Accepts a rule-map array to define many rules compactly. Useful for form-wide validation schemas. ```php $data = [ 'first_name' => 'Bruce', 'last_name' => 'Wayne', 'email' => 'bruce@wayne.com', 'age' => 40, 'bio' => 'Billionaire.', ]; $v = new Validator($data); $v->rules([ 'required' => [ ['first_name'], ['last_name'], ['email'], ], 'alpha' => [['first_name'], ['last_name']], 'email' => [['email']], 'integer' => [['age']], 'min' => [['age', 18]], 'lengthMax' => [['bio', 500]], ]); $result = $v->validate(); // true ``` -------------------------------- ### Define Multiple Rules with Alternate Syntax Source: https://github.com/vlucas/valitron/blob/master/README.md Use an associative array with the `rules` method to define multiple validation rules for different fields at once. ```php $rules = [ 'required' => 'foo', 'accepted' => 'bar', 'integer' => 'bar' ]; $v = new Valitron\Validator(array('foo' => 'bar', 'bar' => 1)); $v->rules($rules); $v->validate(); ``` -------------------------------- ### stopOnFirstFail(bool) Source: https://context7.com/vlucas/valitron/llms.txt Enable or disable validation stopping after the first rule failure. When enabled, only the first encountered error is reported. ```APIDOC ## `stopOnFirstFail(bool)` — Halt After First Failure When enabled, validation stops as soon as the first rule fails, producing at most one error. ```php $v = new Validator(['age' => 'abc']); $v->stopOnFirstFail(true); $v->rule('required', 'age') ->rule('integer', 'age') ->rule('min', 'age', 18); $v->validate(); print_r($v->errors()); // Only one error: ['age' => ['Age must be a valid integer']] ``` ``` -------------------------------- ### Add Multiple Rules at Once Source: https://context7.com/vlucas/valitron/llms.txt Accepts a rule-map array to define many rules compactly. This is particularly useful for validating entire forms using a defined schema. ```APIDOC ## `rules(array $rules)` — Add Multiple Rules at Once Accepts a rule-map array to define many rules compactly. Useful for form-wide validation schemas. ```php $data = [ 'first_name' => 'Bruce', 'last_name' => 'Wayne', 'email' => 'bruce@wayne.com', 'age' => 40, 'bio' => 'Billionaire.', ]; $v = new Validator($data); $v->rules([ 'required' => [ ['first_name'], ['last_name'], ['email'], ], 'alpha' => [['first_name'], ['last_name']], 'email' => [['email']], 'integer' => [['age']], 'min' => [['age', 18]], 'lengthMax' => [['bio', 500]], ]); $result = $v->validate(); // true ``` ``` -------------------------------- ### Alternate 'required' rule syntax Source: https://github.com/vlucas/valitron/blob/master/README.md This demonstrates the alternate syntax for applying the 'required' rule using a 'rules' array. The boolean flag allows empty values if the field name is set. ```php $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(); ``` -------------------------------- ### Alternate syntax for requiredWith rule with strict flag Source: https://github.com/vlucas/valitron/blob/master/README.md Demonstrates the alternate syntax for setting the requiredWith rule with the strict flag enabled. This requires the suffix field only if both first_name and last_name are present. ```php $v = new Valitron\Validator(['first_name' => 'steve', 'last_name' => 'holt', 'suffix' => 'Mr']); $v->rules([ 'requiredWith' => [ ['suffix', ['first_name', 'last_name'], true] ] ]); $v->validate(); ``` -------------------------------- ### Map Rules to Multiple Fields Source: https://github.com/vlucas/valitron/blob/master/README.md Define validation rules for multiple fields simultaneously using an associative array with `mapFieldsRules`. Each key is a field name, and the value is an array of rules. ```php $rules = [ 'foo' => ['required', 'integer'], 'bar'=>['email', ['lengthMin', 4]] ]; $v = new Valitron\Validator(array('foo' => 'bar', 'bar' => 'mail@example.com)); $v->mapFieldsRules($rules); $v->validate(); ``` -------------------------------- ### Validate IPv6 Address Source: https://github.com/vlucas/valitron/blob/master/README.md Use the 'ipv6' rule to verify that a field contains a valid IPv6 address. ```php $v->rule('ipv6', 'user_ip'); ``` ```php $v = new Valitron\Validator(['user_ip' => '0:0:0:0:0:0:0:1']); $v->rules([ 'ipv6' => [ ['user_ip'] ] ]); $v->validate(); ``` -------------------------------- ### Basic 'required' rule usage Source: https://github.com/vlucas/valitron/blob/master/README.md Use the 'required' rule to ensure a field exists and is not null or an empty string. This is the most basic way to enforce a field's presence. ```php $v->rule('required', 'field_name'); ``` -------------------------------- ### Add Array of Field Labels to Rules Source: https://github.com/vlucas/valitron/blob/master/README.md When validating multiple fields with the same rule, use the `labels` method to provide an associative array of field names to their corresponding labels. This method is necessary when a rule applies to an array of fields. ```php $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(); ``` -------------------------------- ### addInstanceRule($name, $callback, $message) Source: https://context7.com/vlucas/valitron/llms.txt Register a custom validation rule specifically for the current `Validator` instance. This allows for closures that capture local variables or context. ```APIDOC ## `addInstanceRule($name, $callback, $message)` — Register an Instance-Scoped Custom Rule Registers a rule only for the current validator instance, allowing closures that capture local variables. ```php $allowedDomains = ['example.com', 'company.org']; $v = new Validator(['email' => 'user@personal.io']); $v->rule('required', 'email')->rule('email', 'email'); $v->addInstanceRule('corporateEmail', function ($field, $value, $params, $fields) use ($allowedDomains) { $domain = substr(strrchr($value, '@'), 1); return in_array($domain, $allowedDomains); }, 'Only corporate email addresses are accepted.'); $v->rule('corporateEmail', 'email'); $v->validate(); // false print_r($v->errors()); // ['email' => ['Email Only corporate email addresses are accepted.']] ``` ``` -------------------------------- ### Per-Field Rule Mapping Source: https://context7.com/vlucas/valitron/llms.txt Attach an ordered list of rules to a single field or a map of fields. Supports inline custom error messages per rule. ```php $v = new Validator(['username' => 'ok', 'email' => 'bad-email']); // Single field $v->mapFieldRules('username', [ 'required', ['lengthMin', 3], ['lengthMax', 20], ['message' => 'Username must be alphanumeric', 'alphaNum'], ]); // Multiple fields at once $v->mapFieldsRules([ 'username' => ['required', 'alphaNum', ['lengthBetween', 3, 20]], 'email' => ['required', 'email'], ]); if (!$v->validate()) { print_r($v->errors()); // ['email' => ['Email is not a valid email address']] } ``` -------------------------------- ### Alternate syntax for requiredWithout rule with strict flag Source: https://github.com/vlucas/valitron/blob/master/README.md Demonstrates the alternate syntax for the requiredWithout rule with the strict flag. This requires the username field only if both first_name and last_name are absent. ```php $v = new Valitron\Validator(['username' => 'BatMan']); $v->rules([ 'requiredWithout' => [ ['username', ['first_name', 'last_name'], true] ] ]); $v->validate(); ``` -------------------------------- ### Alternate 'requiredWith' rule syntax with multiple dependencies Source: https://github.com/vlucas/valitron/blob/master/README.md This alternate syntax for 'requiredWith' uses a 'rules' array to specify that the 'password' field is required if either 'username' or 'email' fields are present and not empty. ```php $v = new Valitron\Validator(['username' => 'spiderman', 'password' => 'Gr33nG0Blin']); $v->rules([ 'requiredWith' => [ ['password', ['username', 'email']] ] ]); $v->validate(); ``` -------------------------------- ### Register Instance-Scoped Custom Rule Source: https://context7.com/vlucas/valitron/llms.txt Register a custom rule only for the current validator instance using `addInstanceRule()`. This allows closures to capture local variables. ```php $allowedDomains = ['example.com', 'company.org']; $v = new Validator(['email' => 'user@personal.io']); $v->rule('required', 'email')->rule('email', 'email'); $v->addInstanceRule('corporateEmail', function ($field, $value, $params, $fields) use ($allowedDomains) { $domain = substr(strrchr($value, '@'), 1); return in_array($domain, $allowedDomains); }, 'Only corporate email addresses are accepted.'); $v->rule('corporateEmail', 'email'); $v->validate(); // false print_r($v->errors()); // ['email' => ['Email Only corporate email addresses are accepted.']] ``` -------------------------------- ### Map Rules to a Single Field Source: https://github.com/vlucas/valitron/blob/master/README.md Assign a list of rules to a specific field using `mapFieldRules`. Rules can be simple strings or arrays for parameterized rules. ```php $rules = [ 'required', ['lengthMin', 4] ]; $v = new Valitron\Validator(array('foo' => 'bar')); $v->mapFieldRules('foo', $rules); $v->validate(); ``` -------------------------------- ### Validate Email with DNS Record Source: https://github.com/vlucas/valitron/blob/master/README.md Use 'emailDNS' to validate an email address and check for an active DNS record. This is useful for ensuring deliverability. ```php $v->rule('emailDNS', 'user_email'); ``` ```php $v = new Valitron\Validator(['user_email' => 'some_fake_email_address@gmail.com']); $v->rules([ 'emailDNS' => [ ['user_email'] ] ]); $v->validate(); ``` -------------------------------- ### Validate IP Address Source: https://github.com/vlucas/valitron/blob/master/README.md Use the 'ip' rule to check if a field contains a valid IP address (IPv4, IPv6, private, or reserved). ```php $v->rule('ip', 'user_ip'); ``` ```php $v = new Valitron\Validator(['user_ip' => '127.0.0.1']); $v->rules([ 'ip' => [ ['user_ip'] ] ]); $v->validate(); ``` -------------------------------- ### Validate IPv4 Address Source: https://github.com/vlucas/valitron/blob/master/README.md Use the 'ipv4' rule to ensure a field is a valid IPv4 address. ```php $v->rule('ipv4', 'user_ip'); ``` ```php $v = new Valitron\Validator(['user_ip' => '127.0.0.1']); $v->rules([ 'ipv4' => [ ['user_ip'] ] ]); $v->validate(); ``` -------------------------------- ### Define Rules Requiring Parameters Source: https://github.com/vlucas/valitron/blob/master/README.md When a rule requires parameters beyond the field name, wrap the rule and its parameters in an array within the rules definition. ```php $rules = [ 'required' => [ ['foo'], ['bar'] ], 'length' => [ ['foo', 3] ] ]; ``` -------------------------------- ### Use Optional Fields in Valitron Source: https://github.com/vlucas/valitron/blob/master/README.md Use the 'optional' rule to ensure a field passes validation only if it's present. If the field is absent, validation for it is skipped. ```php $v->rule('optional', 'username'); ``` -------------------------------- ### Register Static Custom Rule Source: https://context7.com/vlucas/valitron/llms.txt Register a reusable validation rule globally for all `Validator` instances using `Validator::addRule()`. This is typically done once in a bootstrap file. ```php // Register globally (e.g., in a bootstrap file) Validator::addRule('strongPassword', function ($field, $value, array $params, array $fields) { return strlen($value) >= 8 && preg_match('/[A-Z]/', $value) && preg_match('/[0-9]/', $value) && preg_match('/[\W_]/', $value); }, 'Password must be 8+ chars and include uppercase, number, and special character.'); // Use it anywhere $v = new Validator(['password' => 'Weak1']); $v->rule('required', 'password')->rule('strongPassword', 'password'); $v->validate(); // false print_r($v->errors()); // ['password' => ['Password Password must be 8+ chars...']] ``` -------------------------------- ### label($value) / labels(array $labels) Source: https://context7.com/vlucas/valitron/llms.txt Replace machine-readable field names with human-readable labels in error output. Can be set per rule or globally for multiple fields. ```APIDOC ## `label($value)` / `labels(array $labels)` — Human-Readable Field Labels Replace machine field names with readable labels in error output. ```php $v = new Validator(['usr_nm' => '', 'usr_email' => 'bad']); $v->rule('required', 'usr_nm')->label('Username'); $v->rule('required', ['usr_nm', 'usr_email']) ->rule('email', 'usr_email'); $v->labels(['usr_nm' => 'Username', 'usr_email' => 'Email Address']); $v->validate(); print_r($v->errors()); // ['usr_nm' => ['Username is required'], // 'usr_email' => ['Email Address is not a valid email address']] ``` ``` -------------------------------- ### Alternate 'requiredWith' rule syntax Source: https://github.com/vlucas/valitron/blob/master/README.md This shows the alternate syntax for 'requiredWith' using a 'rules' array. It enforces that the 'password' field is required when 'username' is provided and not empty. ```php $v = new Valitron\Validator(['username' => 'spiderman', 'password' => 'Gr33nG0Blin']); $v->rules([ 'requiredWith' => [ ['password', 'username'] ] ]); $v->validate(); ``` -------------------------------- ### Add Custom Static Validation Rule Source: https://github.com/vlucas/valitron/blob/master/README.md Register a new static validation rule using `addRule`. The callback must return a boolean, and an error message can be provided. ```php Valitron\Validator::addRule('alwaysFail', function($field, $value, array $params, array $fields) { return false; }, 'Everything you do is wrong. You fail.'); ``` -------------------------------- ### Use requiredWithout rule Source: https://github.com/vlucas/valitron/blob/master/README.md This rule requires the username field when the first_name is not present. Use when a field is conditionally required based on the absence of another. ```php $v->rule('requiredWithout', 'username', 'first_name'); ``` -------------------------------- ### Validate Active URL Source: https://github.com/vlucas/valitron/blob/master/README.md Use the 'urlActive' rule to check if a URL is valid and has an active DNS record (A, AAAA, or CNAME). ```php $v->rule('urlActive', 'website'); ``` ```php $v = new Valitron\Validator(['website' => 'https://example.com/contact']); $v->rules([ 'urlActive' => [ ['website'] ] ]); $v->validate(); ``` -------------------------------- ### Alternate syntax for requiredWithout rule with multiple fields Source: https://github.com/vlucas/valitron/blob/master/README.md This passes validation because although last_name is not present, the username is provided. Use when checking against multiple potential absent fields. ```php $v = new Valitron\Validator(['username' => 'spiderman', 'first_name' => 'Peter']); $v->rules([ 'requiredWithout' => [ ['username', ['first_name', 'last_name']] ] ]); $v->validate(); ``` -------------------------------- ### Per-Field Rule Mapping Source: https://context7.com/vlucas/valitron/llms.txt Attach an ordered list of rules to a single field or a map of fields. This method also supports inline custom error messages for each rule. ```APIDOC ## `mapFieldRules($field, $rules)` / `mapFieldsRules($rules)` — Per-Field Rule Mapping Attach an ordered list of rules to a single field or a map of fields. Supports inline custom error messages per rule. ```php $v = new Validator(['username' => 'ok', 'email' => 'bad-email']); // Single field $v->mapFieldRules('username', [ 'required', ['lengthMin', 3], ['lengthMax', 20], ['message' => 'Username must be alphanumeric', 'alphaNum'], ]); // Multiple fields at once $v->mapFieldsRules([ 'username' => ['required', 'alphaNum', ['lengthBetween', 3, 20]], 'email' => ['required', 'email'], ]); if (!$v->validate()) { print_r($v->errors()); // ['email' => ['Email is not a valid email address']] } ``` ``` -------------------------------- ### Dot-Notation and Wildcard Validation in PHP Source: https://context7.com/vlucas/valitron/llms.txt Use dot syntax to access nested array values and '*' as a wildcard to validate every element in a list. This is useful for validating complex nested data structures. ```php [ 'first_name' => 'Bruce', 'last_name' => 'Wayne', 'email' => 'bruce@wayne.com', ], ]); $v->rule('required', ['user.first_name', 'user.last_name', 'user.email']) ->rule('alpha', 'user.first_name') ->rule('alpha', 'user.last_name') ->rule('email', 'user.email'); $v->validate(); // true // Wildcard: validate every item in an array $v2 = new Validator([ 'scores' => [85, 92, 101, 78], ]); $v2->rule('integer', 'scores.*') ->rule('min', 'scores.*', 0) ->rule('max', 'scores.*', 100); $v2->validate(); // false — 101 exceeds max print_r($v2->errors()); // ['scores.*' => ['Scores.* must be 100 or less']] ``` -------------------------------- ### Internationalization for Validation Errors in PHP Source: https://context7.com/vlucas/valitron/llms.txt Configure the language for validation error messages globally using `Validator::langDir()` and `Validator::lang()`, or per-instance by passing language and directory to the Validator constructor. ```php 'not-an-email']); $v->rule('required', 'email')->rule('email', 'email'); $v->validate(); print_r($v->errors()); // German error messages // Per-instance language override $v2 = new V(['email' => 'bad'], [], 'fr', __DIR__ . '/vendor/vlucas/valitron/lang'); $v2->rule('email', 'email'); $v2->validate(); // French error messages ``` -------------------------------- ### Validate URL Source: https://github.com/vlucas/valitron/blob/master/README.md The 'url' rule verifies that a field contains a valid URL format. ```php $v->rule('url', 'website'); ``` ```php $v = new Valitron\Validator(['website' => 'https://example.com/contact']); $v->rules([ 'url' => [ ['website'] ] ]); $v->validate(); ``` -------------------------------- ### Check Array Keys with arrayHasKeys Rule Source: https://github.com/vlucas/valitron/blob/master/README.md Ensures a field is an array and contains all specified keys. Returns false if the field is not an array or if any required key is missing. ```php $v = new Valitron\Validator([ 'address' => [ 'name' => 'Jane Doe', 'street' => 'Doe Square', 'city' => 'Doe D.C.' ] ]); $v->rule('arrayHasKeys', 'address', ['name', 'street', 'city']); $v->validate(); ``` -------------------------------- ### Control Label Prepending in Errors Source: https://context7.com/vlucas/valitron/llms.txt Disable the default prepending of field names/labels to error messages by setting `setPrependLabels(false)`. ```php $v = new Validator(['name' => '']); $v->rule('required', 'name'); $v->setPrependLabels(false); $v->validate(); print_r($v->errors()); // ['name' => ['is required']] (no "Name" prefix) ``` -------------------------------- ### Add Individual Field Label to Rule Source: https://github.com/vlucas/valitron/blob/master/README.md Use the `label` method after a rule to assign a specific label to a single field. This is useful for custom error messages. ```php $v = new Valitron\Validator(array()); $v->rule('required', 'name')->message('{field} is required')->label('Name'); $v->validate(); ``` -------------------------------- ### Use requiredWithout rule with multiple fields Source: https://github.com/vlucas/valitron/blob/master/README.md The username field will be required if either the first_name or last_name fields are not present. Use when a field is required if any of a set of other fields are missing. ```php $v->rule('requiredWithout', 'username', ['first_name', 'last_name']); ``` -------------------------------- ### 'required' rule with flexible field existence check Source: https://github.com/vlucas/valitron/blob/master/README.md To make the 'required' rule only check for the field's existence in the data array, pass `true` as the third parameter. This allows null or empty string values as long as the field is present. ```php $v->rule('required', 'field_name', true); ``` -------------------------------- ### Add One-Off Custom Validation Rule Source: https://github.com/vlucas/valitron/blob/master/README.md Define a custom rule directly for specific fields using a closure. This allows access to the surrounding scope's variables. ```php $v = new Valitron\Validator(array("foo" => "bar")); $v->rule(function($field, $value, $params, $fields) { return true; }, "foo")->message("{field} failed..."); ``` -------------------------------- ### Validate Date Before a Specific Date Source: https://github.com/vlucas/valitron/blob/master/README.md Checks if a field's date value is before a specified date. Requires the field and the comparison date. ```php $v->rule('dateBefore', 'created_at', '2018-10-13'); ``` ```php $v = new Valitron\Validator(['created_at' => '2018-09-01']); $v->rules([ 'dateBefore' => [ ['created_at', '2018-10-13'] ] ]); $v->validate(); ``` -------------------------------- ### Validate Date Format Source: https://github.com/vlucas/valitron/blob/master/README.md Use the 'dateFormat' rule to check if a field's date matches a specific format string (e.g., 'Y-m-d'). ```php $v->rule('dateFormat', 'created_at', 'Y-m-d'); ``` ```php $v = new Valitron\Validator(['created_at' => '2018-10-13']); $v->rules([ 'dateFormat' => [ ['created_at', 'Y-m-d'] ] ]); $v->validate(); ``` -------------------------------- ### Validate Field Length Between Source: https://github.com/vlucas/valitron/blob/master/README.md Checks if a field is a string and its length falls within a specified range (inclusive). ```php $v->rule('lengthBetween', 'username', 1, 10); ``` ```php $v = new Valitron\Validator(['username' => 'bobburgers']); $v->rules([ 'lengthBetween' => [ ['username', 1, 10] ] ]); $v->validate(); ``` -------------------------------- ### Use numeric rule Source: https://github.com/vlucas/valitron/blob/master/README.md Checks if the field is a number, analogous to PHP's is_numeric() function. Use for fields that must contain numerical values. ```php $v->rule('numeric', 'amount'); ``` -------------------------------- ### Use requiredWith rule with strict flag Source: https://github.com/vlucas/valitron/blob/master/README.md The strict flag changes requiredWith to require all other fields. Use when suffix is required only when both first_name and last_name are provided. ```php $v->rule('requiredWith', 'suffix', ['first_name', 'last_name'], true); ``` -------------------------------- ### Validator::addRule($name, $callback, $message) Source: https://context7.com/vlucas/valitron/llms.txt Register a static custom validation rule that can be used across all `Validator` instances. The rule is defined by a name, a callback function, and a default error message. ```APIDOC ## `Validator::addRule($name, $callback, $message)` — Register a Static Custom Rule Registers a reusable validation rule available to all future `Validator` instances. ```php // Register globally (e.g., in a bootstrap file) Validator::addRule('strongPassword', function ($field, $value, array $params, array $fields) { return strlen($value) >= 8 && preg_match('/[A-Z]/', $value) && preg_match('/[0-9]/', $value) && preg_match('/[\W_]/', $value); }, 'Password must be 8+ chars and include uppercase, number, and special character.'); // Use it anywhere $v = new Validator(['password' => 'Weak1']); $v->rule('required', 'password')->rule('strongPassword', 'password'); $v->validate(); // false print_r($v->errors()); // ['password' => ['Password Password must be 8+ chars...']] ``` ``` -------------------------------- ### Validate Minimum Field Length Source: https://github.com/vlucas/valitron/blob/master/README.md Checks if a field is a string and meets a minimum length requirement. ```php $v->rule('lengthMin', 'username', 5); ``` ```php $v = new Valitron\Validator(['username' => 'martha']); $v->rules([ 'lengthMin' => [ ['username', 5] ] ]); $v->validate(); ```