Where can you easily hook on validation in Laravel 5.x?
Where can you easily hook on validation in Laravel 5.x?
In Laravel 5.x, you can easily hook into the validation process in several ways:
after
Method on a Validator InstanceThe after
method allows you to attach callbacks that will be executed after the validation process is completed. This is useful for performing additional checks or adding custom error messages. Here is an example:
$validator = Validator::make($data, [
'email' => 'required|email',
]);
$validator->after(function ($validator) {
if ($this->someAdditionalCheckFails()) {
$validator->errors()->add('field', 'Something is wrong with this field!');
}
});
if ($validator->fails()) {
// Handle the failed validation
}
You can add as many after
callbacks as needed to a validator instance[1][4][7].
withValidator
Method in Form Request ClassesForm request classes provide a convenient way to encapsulate validation logic. You can use the withValidator
method to add an "after" validation hook. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are evaluated. Here is an example:
class StoreEventRequest extends FormRequest
{
public function rules()
{
return [
'name' => 'required',
'date' => 'required|date',
];
}
public function withValidator($validator)
{
$validator->after(function ($validator) {
if (strtotime($this->date) < strtotime('now')) {
$validator->errors()->add('date', 'Date should be in the future.');
}
});
}
}
In this example, the withValidator
method is used to add a custom validation rule that checks if the date is in the future[4][8][10].
You can create custom validation rules using rule objects or by extending the Validator
facade. For example, to create a custom rule object:
php artisan make:rule Uppercase
// In app/Rules/Uppercase.php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Uppercase implements Rule
{
public function passes($attribute, $value)
{
return strtoupper($value) === $value;
}
public function message()
{
return 'The :attribute must be uppercase.';
}
}
// Using the custom rule in a request
$request->validate([...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào