thedevdojo / voyager

Voyager - The Missing Laravel Admin
https://voyager.devdojo.com
MIT License
11.78k stars 2.67k forks source link

Custom validation rule for a field #5265

Closed howdu closed 3 years ago

howdu commented 3 years ago

It would be great to have a way of setting custom validation rules to a field without overwriting the controller. https://voyager-docs.devdojo.com/bread/introduction#validation

E.g

{
    "validation": {
        "rule": "required",
        "custom_rule": "App\Rules\DateWithinFinancialYear|App\Rules\SlugUniqueForCategory",
        "messages": {
            "required": "This :attribute field is a must."
        }
    }
}
MrCrayon commented 3 years ago

There is no need to override Controller, create a custom rule and apply it like any other rule.

howdu commented 3 years ago

Please could you give example because I can only make it work with default laravel validation.

E.g using a custom validation rule

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class DateWithinFinancialYear implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return false; // always fail for testing
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be ....';
    }
}

Update the field details:

{
    "validation": {
        "rule": "required|DateWithinFinancialYear",
        "messages": {
            "required": "This :attribute field is a must."
        }
    }
}

Throws error: Method Illuminate\Validation\Validator::validateDateWithinFinancialYear does not exist.

MrCrayon commented 3 years ago
// in Provider boot method

//Custom validation rule
Validator::extend('date_with_financial_year', function ($attribute, $value, $parameters, $validator) {
    //your checks
}, 'custom message');
{
  "validation": {
    "rule": "required|date_with_financial_year",
  }
}
howdu commented 3 years ago

Awesome thanks that's exactly what I needed. It's not in the laravel 8 documentation but exists in the older ones so might be worth adding it into the voyager documentation.

github-actions[bot] commented 1 year ago

This issue has been automatically locked since there has not been any recent activity after it was closed. If you have further questions please ask in our Slack group.