How to add custom form validation in laravel?

by hal.littel , in category: PHP Frameworks , 3 months ago

How to add custom form validation in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , 3 months ago

@hal.littel 

To add custom form validation in Laravel, you can follow these steps:

  1. 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.

  1. 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
}


  1. 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.';
}


  1. 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],
]);


  1. 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.