@hal.littel
To add custom form validation in Laravel, you can follow these steps:
- Create a new custom validation rule by running the following command in your terminal:
1
|
php artisan make:rule CustomRule
|
This will create a new file under the app/Rules directory with the name CustomRule.php.
- Open the CustomRule.php file and define the custom validation rule logic inside the passes method. For example:
1
2
3
4
5
|
public function passes($attribute, $value)
{
// Custom validation logic
return true; // return true if validation passes, false if it fails
}
|
- You can also add a custom error message for your validation rule by adding a message method to the CustomRule class:
1
2
3
4
|
public function message()
{
return 'The :attribute is not valid.';
}
|
- Once you have created your custom validation rule, you can use it in your validation logic by adding it to the validation rules array in your controller or form request class. For example:
1
2
3
|
$validatedData = $request->validate([
'name' => ['required', new CustomRule],
]);
|
- That's it! Your custom form validation rule is now added to your Laravel application and will be applied to any form that uses it. You can create and use as many custom validation rules as needed to suit your application's requirements.