custom validation in laravel


'job_id' => 'integer',
'assignment_id' => 'integer',
'assigned_to' => 'string|exists:users,username',
'sort_by' => 'required_with:order|string',
'order' => 'string|in:asc,desc',
'start_date' => 'required_with:end_date|date_format:"Y-m-d"|before_or_equal:end_date',
'end_date' => 'required_with:start_date|date_format:"Y-m-d"|after_or_equal:start_date',
'assignments_per_page' => 'integer|in:1,10,25,50,100',
'level' => 'integer',
'input_filters' => 'array',
'input_filters.*.column' => 'required|string',
'input_filters.*.value' => 'required',
'output_filters' => 'array',
'output_filters.*.column' => 'required|string',
'output_filters.*.value' => 'string|nullable'


In Laravel, you can create custom validations by defining your own validation rules. Here's a step-by-step guide on how to create custom validations in Laravel:

  1. Create a new validation rule class: Run the following command to generate a new custom validation rule class:

php artisan make:rule CustomRule

  1. This command will create a new CustomRule class inside the App\Rules directory.

  2. Open the generated CustomRule class and implement the Illuminate\Contracts\Validation\Rule interface. This interface requires you to define two methods: passes() and message().


 s

?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class CustomRule implements Rule
{
    public function passes($attribute, $value)
    {
        // Define your custom validation logic here
        // Return true if the value passes the validation, false otherwise
    }

    public function message()
    {
        return 'The validation error message.';
    }
}

s

  1. Implement your custom validation logic inside the passes() method. This method receives the attribute name and the value being validated. Write your validation logic and return true if the value passes the validation, or false if it fails.

  2. Define the error message for your custom validation rule in the message() method. Return the error message you want to display when the validation fails.

  3. To use your custom validation rule, you can include it in your validation rules array in your controller or form request.


 s

use App\Rules\CustomRule;

//...

$validatedData = $request->validate([
    'field_name' => ['required', new CustomRule],
]);


s


That's it! You've created a custom validation rule in Laravel. Now, whenever the validation is triggered, your custom rule will be applied, and if it fails, the error message you specified will be displayed.


 

No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...