kalshah/laravel-validation-html-attributes

使用Laravel后端验证规则作为HTML验证属性。

0.0.1 2021-08-05 21:15 UTC

This package is not auto-updated.

Last update: 2024-09-29 20:38:16 UTC


README

此包提供了一种简单、智能的方法,将Laravel验证规则传递给HTML表单,并用作客户端验证。

安装

此包可以通过Composer安装

composer require kalshah/laravel-validation-html-attributes

工作原理

核心工作是在一个特性 WithHtmlAttributes 中完成的,它可以通过两种方式使用

1- 首先使用包请求 LaravelValidationToHtmlAttributesRequest,它使用这个特性,如果你在控制器方法中验证请求,这适合你

    public function create(LaravelValidationToHtmlAttributesRequest $request)
    {
        $request->setRules([
            'first_name' => 'required'
        ]);
        
        return view('form', ['attributes' => $request->htmlAttributes()]);
    }

2- 第二种方式是在你的 FormRequest 中使用 WithHtmlAttributes

    use WithHtmlAttributes;

在你的控制器中,你可以这样传递属性

    public function create()
    {
        return view('form', ['attributes' => (new WithHtmlAttributesFormRequest())->htmlAttributes()]);
    }

在blade文件中,你可以访问这些属性并将它们添加到HTML表单输入中,如下所示

<input name="first_name" {{ $attributes->first_name }}>

假设这个字段的Laravel验证规则是 first_name

return ['first_name' => 'required|min:2|string'];

返回的HTML验证输入将是

<input name="first_name" required="required" minlength="2" type="string">

正如我们所见,这个特性将Laravel验证规则转换成了有效的HTML验证属性。