Skip to main content
Version: CANARY 🚧

Data Validation

Introduction​

Data validation is a crucial part of any web application. BowPHP provides a simple, elegant, and powerful validation system that lets you easily validate your incoming data.

Basic Usage​

Tip

The simplest way to use the validator is through the validator() helper function. Here is a simple example:

$data = [
"name" => "John Doe",
"email" => "john@example.com",
"age" => 25
];

$validation = validator($data, [
"name" => "required|min:3|max:50",
"email" => "required|email",
"age" => "required|int"
]);

if ($validation->fails()) {
// Validation failed
$errors = $validation->getMessages();
// Handle the errors
}

Available Validation Rules​

Rules

BowPHP offers a wide range of validation rules to cover most common validation needs.

Basic Rules​

RuleDescription
requiredThe field is required
required_if:field1,field2The field is required if the specified fields exist
nullableThe field may be null or absent (short-circuits the following rules)
confirmedThe field must match the <name>_confirmation field
different:fieldThe field must be different from another field
same:valueThe field must be identical to the specified value
in:val1,val2,...The value must be part of the given list
emailThe field must be a valid email address
min:valueThe minimum length of the field
max:valueThe maximum length of the field
size:valueThe exact length of the field
between:min,maxValue (numeric) or length (string) between min and max inclusive
nullable combined with required

By default, nullable stops the execution of the following rules as soon as it matches. Exception: if required also appears in the chain, required runs anyway. This allows you to write nullable|required to mean "must be present even if empty" and keep the semantics expected by users.

Type Rules​

RuleDescription
alphaAlphabetic characters only
alphanumAlphanumeric characters only
numberThe field must be a number
intThe field must be an integer
floatThe field must be a decimal number
boolean / boolAccepts true, false, 0, 1, '0', '1', 'true', 'false'
jsonThe field must be a valid JSON string
uuidThe field must be a canonical UUID (versions 1 to 5)

Format Rules​

RuleDescription
dateDate format (YYYY-MM-DD)
datetimeDatetime format (YYYY-MM-DD HH:MM:SS)
regex:patternThe field must match the regex pattern
lowerLowercase letters only
upperUppercase letters only
urlThe field must be a well-formed URL (filter_var FILTER_VALIDATE_URL)
ipThe field must be an IPv4 or IPv6 address
ip:v4The field must be an IPv4 address only
ip:v6The field must be an IPv6 address only

Database Rules​

RuleDescription
unique:table,columnThe value must be unique in the table
exists:table,columnThe value must exist in the table
!exists:table,columnThe value must not exist in the table

Custom Error Messages​

Customization

You can customize the error messages by passing an array of messages as the third argument:

$validation = validator($data, [
"name" => "required|min:3",
"email" => "required|email"
], [
"name" => [
"required" => "Le nom est obligatoire",
"min" => "Le nom doit contenir au moins 3 caractères"
],
"email" => [
"required" => "L'email est obligatoire",
"email" => "L'email n'est pas valide"
]
]);

Retrieving Errors​

Available Methods

The validator provides several methods to retrieve information about the errors:

// Checks whether validation failed
$validation->fails(); // bool

// Retrieves all error messages
$validation->getMessages(); // array

// Retrieves the last error message
$validation->getLastMessage(); // string

// Retrieves the fields that failed
$validation->getCorruptedFields(); // array

// Retrieves the rules that failed
$validation->getFailsRules(); // array

Validation and Exceptions​

Exceptions

You can throw a validation exception with the throwError() method:

$validation = validator($data, $rules);

if ($validation->fails()) {
$validation->throwError(); // Throws ValidationException
}

The exception will contain the error messages and will automatically set the HTTP status code to 400.

Validation in Controllers​

Here is a practical example of using the validator in a controller:

class UserController
{
public function store()
{
$validation = validator(request()->all(), [
"name" => "required|min:3|max:50",
"email" => "required|email|unique:users,email",
"password" => "required|min:6"
]);

if ($validation->fails()) {
return response()->json([
"errors" => $validation->getMessages()
], 400);
}

// Create the user
User::create(request()->all());

return response()->json([
"message" => "User created successfully"
]);
}
}

Best Practices​

Recommendations

Follow these best practices for effective and secure validation:

  1. Early validation: Validate data as early as possible in the request lifecycle.
  2. Clear messages: Use descriptive and understandable error messages.
  3. Composed rules: Combine multiple rules for robust validation.
  4. Security: Always use server-side validation, even if you have client-side validation.

Is something missing?

If you run into problems with the documentation or have suggestions to improve the documentation or the project in general, please open an issue for us, or send a tweet mentioning the Twitter account @bowframework or directly on github.