簡體   English   中英

Laravel 5.7:用於表單驗證的自定義屬性不起作用

[英]Laravel 5.7: Custom attributes for form validation not working

我想同時使用自定義消息和屬性來驗證表單。 代替name: The name may not be greater than 20 characters. 用戶應該看到Name: Please use fewer characters. , 例如。

我正在使用AJAX以及Laravel返回的response.data.errors對象的鍵和值。 我正在使用Laravel 5.7。

這是我RegisterController validator功能的簡化版本。

protected function validator(array $data)
{
    // Nice attribute names
    $attributes = [
        'name' => 'Name',
        // ...
    ];

    // Custom messages
    $messages =  [
        'max' => 'Please use fewer characters.'
        // ...
    ];

    // Rules
    $rules = [
        'name'=> 'required|max:20',
        // ...
    ];

    // Working for messages, but not for attribute names
    $validator = Validator::make($data, $rules, $messages, $attributes);

    // Also not working
    // $validator->setAttributeNames($attributes);

    return $validator;
}

發生驗證錯誤時,用戶會收到一條消息,如name: Please use fewer characters. 這意味着將顯示來自我的自定義數組的消息,但使用默認屬性名稱。 怎么了

屬性不會替換鍵名,它們用於更改消息中鍵的外觀(即The Name field is required ,以實現您要在問題中嘗試做的事情,您需要創建一個新的數據數組。


protected function validator(array $data)
{
    $data = [
        'Name' => $data['name'] ?? '',
        // ...
    ];

    // ...

    Validator::make($data, $rules, $messages);
}

這來自resources / Lang / xx /中的validation.php。

編輯:

您必須使用

$messages = [ 'name.max' => 'Your sentence here', ];

您必須向所有驗證規則發送消息。

// Custom messages
$messages =  [
    'name.required' => 'The name field is required',
    'name.max:20' => 'Please use less characters.'
    // ...
];

使用Laravel表單請求 ,向下滾動到“ Customizing The Error Messages部分。 查看以下示例代碼。

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UserRegistrationForm extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|max:20',
        ];
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'name.max' => 'Please use less characters'
        ];
    }
}

在控制器中

public function register(UserRegistrationForm $request)
    {
         // do saving here
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM