Question:
Creating custom required rule - Laravel validation

Problem:

I have created custom required rule which checks if field is marked as true and is empty then it will fails validation.

It is working fine for required fields i.e. fields which are marked as required. But for other fields which are optional I am getting error like 'The field must be string'. Because it is not set as nullable. If I add nullable then my custom rule is being ignored.

How can I achieve my purpose like if field is not required then it should treat it as nullable.

Below is rule:

'name' => [

    new RequiredRule(),

    'string',

],


Below is RequiredRule:

namespace App\Rules;


use Closure;

use App\Models\RuleTable;

use Illuminate\Contracts\Validation\ValidationRule;


final class RequiredRule implements ValidationRule

{

    public function validate(string $attribute, mixed $value, Closure $fail): void

    {

        $attribute = RuleTable::query()->where('field', $attribute)->first();

        

        if ($attribute->required && empty($value)) {

            $fail("The {$attribute->display_name} field is required.");

        }

    }

}


Solution:

For optional fields, you can use sometimes validation:

Run validation checks against a field only if that field is present in the data being validated.


This means, if you don't submit an input, the String validation rule won't be applied to it. You can do it like this:

'name' => [

    'sometimes',

    new RequiredRule(),

    'string',

],

In the example above, the name field will only be validated if it is present in the data that you're submitting.


Answered By: >zlatan

Credit: >Stack Overflow


Suggested blogs:

>How to Build a RESTful API Using Node Express and MongoDB- Part 1

>How to build an Electron application from scratch?

>How to build interactive_graphviz in Python

>How to change the project in GCP using CLI command

>How to create a line animation in Python?


Ritu Singh

Ritu Singh

Submit
0 Answers