Error Messages
Valicomb provides flexible error message handling with custom messages, field labels, and message placeholders.
Getting Errors
Section titled “Getting Errors”After validation runs, you’ll need to retrieve any errors that occurred. Valicomb provides several methods to access errors, whether you want all of them at once, errors for a specific field, or just need to check if validation passed.
Get All Errors
Section titled “Get All Errors”$v = new Validator($_POST);$v->rule('required', 'email');$v->rule('integer', 'age');
if (!$v->validate()) { $errors = $v->errors(); // [ // 'email' => ['Email is required'], // 'age' => ['Age must be an integer'] // ]}Get Errors for Specific Field
Section titled “Get Errors for Specific Field”$emailErrors = $v->errors('email');// ['Email is required', 'Email is not a valid email address']
// Returns false if no errors for field$nameErrors = $v->errors('name'); // falseCheck if Validation Passed
Section titled “Check if Validation Passed”if ($v->validate()) { // All rules passed $data = $v->data();} else { // At least one rule failed $errors = $v->errors();}Custom Error Messages
Section titled “Custom Error Messages”Default error messages work for most cases, but sometimes you need messages that match your application’s tone or provide more specific guidance. You can override any rule’s default message with your own.
Per-Rule Messages
Section titled “Per-Rule Messages”Override the default message for a specific rule:
$v = new Validator($_POST);$v->rule('required', 'email')->message('We need your email!');$v->rule('email', 'email')->message("That doesn't look like a valid email");Chain Multiple Rules
Section titled “Chain Multiple Rules”$v->rule('required', 'password') ->message('Password cannot be empty') ->rule('lengthMin', 'password', 8) ->message('Password must be at least 8 characters long');Message Placeholders
Section titled “Message Placeholders”Placeholders let you create dynamic error messages that include the field name, the invalid value, and rule parameters. This makes error messages more informative without hardcoding values.
Error messages support placeholder substitution:
| Placeholder | Description |
|---|---|
{field} | The field name or custom label |
{value} | The actual value that failed validation |
%s, %d | sprintf-style placeholders for rule parameters |
Basic Placeholders
Section titled “Basic Placeholders”$v->rule('lengthBetween', 'username', 3, 20) ->message('{field} must be between %d and %d characters');// Result: "Username must be between 3 and 20 characters"
$v->rule('min', 'age', 18) ->message('{field} must be at least %s years old');// Result: "Age must be at least 18 years old"The {value} Placeholder
Section titled “The {value} Placeholder”Include the actual failed value in error messages for more helpful feedback:
$v = new Validator(['email' => 'not-an-email']);$v->rule('email', 'email') ->message('{field} "{value}" is not a valid email address');$v->validate();// Error: 'Email "not-an-email" is not a valid email address'Value Formatting
Section titled “Value Formatting”The {value} placeholder automatically formats different types:
| Type | Display |
|---|---|
| String | The string value |
| Integer/Float | The numeric value |
null | ”null” |
true | ”true” |
false | ”false” |
| Array | JSON representation |
| DateTime | ”Y-m-d H:i:s” format |
| Object | Class name |
Examples with Different Types
Section titled “Examples with Different Types”// String value$v = new Validator(['code' => 'ABC']);$v->rule('integer', 'code')->message('{field} "{value}" must be an integer');// Error: 'Code "ABC" must be an integer'
// Null value$v = new Validator(['field' => null]);$v->rule('required', 'field')->message('{field} cannot be {value}');// Error: 'Field cannot be null'
// Boolean value$v = new Validator(['active' => true]);$v->rule('email', 'active')->message('{field} value {value} is invalid');// Error: 'Active value true is invalid'
// Numeric value$v = new Validator(['age' => 15]);$v->rule('min', 'age', 18)->message('{field} "{value}" must be at least %s');// Error: 'Age "15" must be at least 18'Combining All Placeholders
Section titled “Combining All Placeholders”$v = new Validator(['score' => 150]);$v->rule('max', 'score', 100) ->message('{field} value "{value}" exceeds maximum of %s') ->label('Player Score');$v->validate();// Error: 'Player Score value "150" exceeds maximum of 100'Manual Error with {value}
Section titled “Manual Error with {value}”When adding errors programmatically, pass the value as the fourth parameter:
$v = new Validator(['username' => 'admin']);
// Custom validationif ($username === 'admin') { $v->error('username', '{field} "{value}" is reserved', [], 'admin');}// Error: 'Username "admin" is reserved'Field Labels
Section titled “Field Labels”Field names in your code often use snake_case or technical names that don’t look great in user-facing error messages. Labels let you define human-readable names that appear in error messages instead.
Make error messages more user-friendly with custom field labels.
Single Label
Section titled “Single Label”$v->rule('required', 'email_address') ->label('Email Address');// Error: "Email Address is required" instead of "Email address is required"Multiple Labels
Section titled “Multiple Labels”$v->labels([ 'email' => 'Email Address', 'password' => 'Password', 'first_name' => 'First Name', 'last_name' => 'Last Name']);Labels with Rules
Section titled “Labels with Rules”$v = new Validator($_POST);$v->labels([ 'user_email' => 'Email Address', 'user_pass' => 'Password']);$v->rule('required', ['user_email', 'user_pass']);$v->rule('email', 'user_email');Hiding Field Labels
Section titled “Hiding Field Labels”In some contexts (like API responses or single-field forms) you may not want field names prepended to error messages. You can disable this behavior globally for a validator instance.
By default, error messages are prefixed with the field name. You can disable this:
$v = new Validator(['email' => 'invalid']);$v->setPrependLabels(false);$v->rule('email', 'email');$v->validate();// Error: "is not a valid email address" (no "Email" prefix)When to Hide Labels
Section titled “When to Hide Labels”- Building JSON API responses where you already know the field
- Custom error display where you show field names separately
- Single-field forms
Manually Adding Errors
Section titled “Manually Adding Errors”Sometimes you need to add errors based on custom logic that isn’t covered by built-in rules—like checking against a database or validating business rules. You can add errors programmatically and they’ll be included with the other validation errors.
Add custom errors programmatically:
$v = new Validator($_POST);
// Custom validation logicif ($someCustomCondition) { $v->error('field_name', 'This field failed custom validation');}
// With sprintf placeholders$v->error('age', 'Must be between %d and %d', [18, 65]);
// With {value} placeholder (pass value as 4th parameter)$v->error('username', '{field} "{value}" is not allowed', [], $username);Error Display Patterns
Section titled “Error Display Patterns”How you display errors depends on your application’s UI. Here are common patterns for rendering validation errors in different contexts.
Simple List
Section titled “Simple List”if (!$v->validate()) { echo '<ul class="errors">'; foreach ($v->errors() as $field => $messages) { foreach ($messages as $message) { echo "<li>$message</li>"; } } echo '</ul>';}Field-Specific Display
Section titled “Field-Specific Display”function displayFieldError($v, $field) { $errors = $v->errors($field); if ($errors) { return '<span class="error">' . $errors[0] . '</span>'; } return '';}
// In your formecho '<input name="email">' . displayFieldError($v, 'email');JSON API Response
Section titled “JSON API Response”if (!$v->validate()) { http_response_code(422); echo json_encode([ 'success' => false, 'errors' => $v->errors() ]); exit;}First Error Only
Section titled “First Error Only”if (!$v->validate()) { $allErrors = $v->errors(); $firstField = array_key_first($allErrors); $firstError = $allErrors[$firstField][0]; echo $firstError;}Internationalization
Section titled “Internationalization”Valicomb includes translations for 33 languages out of the box. You can set the language globally or per-instance to display error messages in your users’ preferred language.
Error messages support multiple languages:
// Set global languageValidator::lang('es'); // Spanish
// Or per-instance$v = new Validator($data, [], 'fr'); // FrenchSee Internationalization Guide for more details.