expand_less

Validation

Introduction

Dreamfork provides various approaches to validate your application's incoming data. While the validate method on HTTP requests is a common choice, Dreamfork offers flexibility with other validation methods.

Dreamfork's validation includes a broad range of rules, making it convenient to validate data. This section will delve into each validation rule to familiarize you with Dreamfork's validation capabilities.

Validation Quickstart

To grasp Dreamfork's validation features, let's explore a comprehensive example of validating a form and presenting error response to the user. This high-level overview will provide a solid understanding of how to validate incoming request data in Dreamfork.

Let's assume we have a route handling post creation and a PostController.

Writing The Validation Logic

Now, let's populate our store method with logic to validate the new blog post. We will utilize the validate method provided by the Framework\Http\Request object. If the validation rules pass, your code will proceed as usual. However, if validation fails, Dreamfork will throw an Framework\Services\Validator\Exceptions\ValidationException exception, and the appropriate error response will be automatically sent to the user.

To get a better understanding of the validate method, let's jump back into the store method:

                                
                                    
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required|string|max:255',
'body' => 'required',
]);
// The blog post is valid...
// ...
}

Validation Rules in Dreamfork are passed into the validate method. If the validation fails, the appropriate response is automatically generated. On successful validation, the controller proceeds with its normal execution.

Another approach is to specify validation rules as arrays instead of a single | delimited string:

                                
                                    
$validated = $request->validate([
'title' => ['required', 'string', 'max:255'],
'body' => ['required'],
]);

Request Validation

As demonstrated earlier, validation can be directly performed on the $request object by passing a list of rules as an argument. All available rules are documented. Utilizing validation directly on the $request object requires the validation to succeed; otherwise, Dreamfork will automatically halt further code execution.

                                
                                    
$validated = $request->validate([
'title' => 'required|string|max:255',
'body' => ['required'],
]);

Custom Messages

It is possible to define custom error messages for validation. To achieve this, pass an array of messages as the second parameter to the validate method.

                                
                                    
$validated = $request->validate(
[
'title' => ['required', 'string', 'max:255'],
'body' => ['required'],
],
[
'title.required' => 'You need to specify title!',
]
);

Custom Attributes

It is also possible to define custom attribute names, which will be used in the error message instead of the original attribute names. To achieve this, pass an array of attribute names as the third parameter to the validate method.

                                
                                    
$validated = $request->validate(
[
'title' => ['required', 'string', 'max:255'],
'body' => ['required'],
],
[
],
[
'title' => 'post title',
]
);

Accessing Validated Data

The validate method returns an array, allowing you to access the validated data using keys, for example:

                                
                                    
$validated = $request->validate(
[
'title' => ['required', 'string', 'max:255'],
'body' => ['required'],
]
);
 
echo $validated['title'];

Manually Creating Validators

If you prefer not to use the validate method on a request, you can create a validator instance using the Validator facade. The make method on the facade generates a new validator instance. The first argument passed to make is the data to be validated, followed by the validation rules as subsequent arguments, similar to the validate method.

                                
                                    
use Framework\Support\Facades\Validator;
 
$validator = Validator::make($request->all(), [
'title' => ['required', 'string', 'max:255'],
'body' => ['required'],
]);

In the case of such a validator, validation is not performed automatically, and you need to explicitly execute it.

Manual Validation Execution

When manually executing validation using the Validator facade in Dreamfork, the process involves checking whether the validation failed. This approach provides the advantage of allowing you to handle validation failures according to your specific requirements, instead of automatically generating a response as seen with the validate method on the request:

                                
                                    
use Framework\Support\Facades\Validator;
 
$validator = Validator::make($request->all(), [
'title' => ['required', 'string', 'max:255'],
'body' => ['required'],
]);
 
if ($validator->fails()) {
$errors = $validator->getMessages();
// ...
}

If you do not need to handle validation failures in a custom way, you can use the throw method. This method allows you to achieve the same effect as when validation fails with the validate method on the request - the code execution will be halted, and a response with details of the validation failure will be generated.

                                
                                    
use Framework\Support\Facades\Validator;
 
$validator = Validator::make($request->all(), [
'title' => ['required', 'string', 'max:255'],
'body' => ['required'],
]);
 
if ($validator->fails()) {
$validator->throw();
}

Accessing Validated Data

After handling potential validation failures, you can access the validated data using the safe() method in Dreamfork. This method allows you to retrieve specific attributes by using only() or exclude certain attributes using except().

                                
                                
// Access validated data using safe()
$title = $validator->safe()->title;
 
// Access validated data using safe()->only()
$title = $validator->safe()->only(['author', 'title'])['title'];
 
// Access validated data using safe()->except()
$author = $validator->safe()->except(['title'])['author'];

You can also access all validated attributes using the validated() method in Dreamfork.

                                
                                    
$validated = $validator->validated();

Available Validation Rules

Below is a list of all available validation rules and their function:

array

The field under validation must be a PHP array.

When using the array rule, you can provide additional values that serve as a whitelist. Each key in the input array must be present within the list of values provided to the rule. Here's an example to illustrate this:

                                
                                    
$input = [
'post' => [
'title' => 'Some title',
'body' => 'Content of post',
],
];
 
$validator = Validator::make($input, [
'post' => 'array:title',
]);

In this example, the body key was defined within the array rule, but it was not supplied to the validator. It's crucial to note that if any keys are omitted from the array rule, the validation will fail. Therefore, it is mandatory to explicitly specify all the array keys that are expected during validation to ensure a successful validation process.

boolean

The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".

confirmed

The field under validation must have a matching field of {field}_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.

decimal:min,max

The field under validation must be numeric and must contain the specified number of decimal places:

                                
                                    
// Must have exactly two decimal places (9.99)...
'price' => 'decimal:2'
// Must have between 2 and 4 decimal places...
'price' => 'decimal:2,4'

email

The field under validation must be formatted as an email address.

ends_with:foo,bar,...

The field under validation must end with one of the given values.

file

The field under validation must be a successfully uploaded file.

gt:field

The field under validation must be greater than the given field or value. The two fields must be of the same type.

gte:field

The field under validation must be greater than or equal to the given field or value. The two fields must be of the same type.

in:foo,bar,...

The field under validation must be included in the given list of values. Since this rule often requires you to implode an array, the Rule::in method may be used to fluently construct the rule:

                                
                                    
use Framework\Services\Validator\Rule;
 
$validator = Validator::make($request->all(), [
'title' => ['required', 'string', 'max:255'],
'category' => ['required', Rule::in(['it', 'educational'])],
]);

integer

The field under validation must be an integer.

This validation rule does not specifically check whether the input is of the "integer" variable type. Instead, it verifies that the input conforms to the type accepted by PHP's FILTER_VALIDATE_INT rule. If you need to validate the input as a number, it is recommended to use this rule in conjunction with the numeric validation rule.

ip

The field under validation must be an IP address.

lowercase

The field under validation must be lowercase.

lt:field

The field under validation must be less than the given field or value. The two fields must be of the same type.

lte:field

The field under validation must be less than or equal to the given field or value. The two fields must be of the same type.

max:value

The field under validation must be less than or equal to a maximum value.

min:value

The field under validation must have a minimum value.

not_in:foo,bar,...

The field under validation must not be included in the given list of values. The Rule::notIn method may be used to fluently construct the rule:

                                
                                    
use Framework\Services\Validator\Rule;
 
$validator = Validator::make($request->all(), [
'title' => ['required', 'string', 'max:255'],
'category' => ['required', Rule::notIn(['lifestyle', 'cooking'])],
]);

not_regex:pattern

The field under validation must not match the given regular expression.

Internally, this rule uses the PHP preg_match function. The pattern specified should obey the same formatting required by preg_match and thus also include valid delimiters. For example: 'email' => 'not_regex:/^.+$/i'.

When using the regex / not_regex patterns, it may be necessary to specify your validation rules using an array instead of using | delimiters, especially if the regular expression contains a | character.

nullable

The field under validation may be null.

numeric

The field under validation must be numeric.

regex:pattern

The field under validation must match the given regular expression.

Internally, this rule uses the PHP preg_match function. The pattern specified should obey the same formatting required by preg_match and thus also include valid delimiters. For example: 'email' => 'not_regex:/^.+$/i'.

When using the regex / not_regex patterns, it may be necessary to specify your validation rules using an array instead of using | delimiters, especially if the regular expression contains a | character.

required

The field under validation must be present in the input data and not empty. A field is "empty" if it meets one of the following criteria:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with no path.

same

The given field must match the field under validation.

size:value

The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value (the attribute must also have the numeric or integer rule). For an array, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes. Let's look at some examples:

                                
                                    
// Validate that a string is exactly 12 characters long...
'title' => 'size:12';
 
// Validate that a provided integer equals 10...
'seats' => 'integer|size:10';
 
// Validate that an array has exactly 5 elements...
'tags' => 'array|size:5';
 
// Validate that an uploaded file is exactly 512 kilobytes...
'image' => 'file|size:512';

starts_with:foo,bar,...

The field under validation must start with one of the given values.

sometimes

In some situations, you may wish to run validation checks against a field only if that field is present in the data being validated. To quickly accomplish this, use this rule.

string

The field under validation must be a string. If you would like to allow the field to also be null, you should assign the nullable rule to the field.

uppercase

The field under validation must be uppercase.