Laravel 自定义验证规则修正

问题描述 投票:0回答:2

我正在我的 app/Rules 命名空间中创建一个 laravel 自定义 Uppercase.php 规则,以检查提交的标题是否以大写字母开头,如果不是,则应抛出错误/失败。

   class ArticleController extends Controller
    {
        public function store(Request $request)
        {
            $request->validate([
      
                'title' => ['required', new Uppercase()]
            ]);
    
            Article::create(['title' => $request->title]);
        }
    }
    
    

这是Uppercase.php 类中的代码。 我正在尝试检查标题第一个字符是否大写

    use Closure;
    use Illuminate\Contracts\Validation\ValidationRule;
    
    class Uppercase implements ValidationRule
    {
        
        public function validate(string $attribute, mixed $value, Closure $fail): void
        {
        if (ucfirst($value) !== $value) {
                $fail("The $attribute must start with an uppercase letter.");
            }
        }
    }

更多详情

运行测试时,仍然失败

php laravel laravel-validation
2个回答
2
投票

您可以使用以下一项更改验证。值首先转换为小写,然后应用

ucfirst

use Closure;
use Illuminate\Contracts\Validation\Rule;

class Uppercase implements Rule
{
    public function passes($attribute, $value)
    {
        $firstCharOfTitle = Str::substr($value, 0, 1);
        return Str::ucfirst($firstCharOfTitle) === $firstCharOfTitle;
    }

    public function message()
    {
        return 'The :attribute must start with an uppercase letter.';
    }
}

我想知道为什么要创建自定义验证规则来检查第一个字符是否为大写。

将值存储到数据库时,您可以应用与下面相同的转换。

Article::create(['title' => Str::ucfirst($request->title)]);

确保导入

Illuminate\Support\Str


1
投票

你也可以这样使用。

use Closure;
use Illuminate\Contracts\Validation\Rule;

class Uppercase implements Rule 
{
    public function passes($attribute, $value)
    {
        if (empty($value)) {
            return false;
        }

        $firstCharacter = $value[0];
        return $firstCharacter === strtoupper($firstCharacter);
    }

    public function message()
    {
        return 'The :attribute must start with an uppercase letter.';
    }
}

在控制器中

class ArticleController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'title' => ['required', new Uppercase()]
        ]);

        Article::create(['title' => $request->title]);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.