laravel-5 - 如何对 2 个字段产生一个验证错误
问题描述
我有 2 个用于邮政编码主要和次要的字段。
<input type="text" name="postal01">
<input type="text" name="postal02">
我想验证添加的两个字段的数字和大小。我想要做的是将一个字段的验证错误显示为 postal_cd,而不是每个字段错误。
我曾在请求类扩展 FormRequest 中尝试过。
class MemberRequest extends FormRequest
{
public function all($keys = null)
{
$result = parent::all($keys);
if($this->filled('postal01') && $this->filled('postal02')) {
$results['postal_code'] = $this->input('postal01') . $this->input('postal02');
}
return $result;
}
然而它并没有像我预期的那样工作。
我该如何处理这种情况?
解决方案
您可以使用After Validation Hook。将以下内容添加到您的表单请求中:
/**
* Configure the validator instance.
*
* @param \Illuminate\Validation\Validator $validator
* @return void
*/
public function withValidator($validator)
{
$validator->after(function ($validator) {
if($validator->errors()->has('postal01') || $validator->errors()->has('postal02')) {
$validator->errors()->add('postal_cd', 'Please enter a postal code');
}
});
}
...然后将其显示在刀片上:
{{ $errors->first('postal_cd') }}
推荐阅读
- r - R, 3-way table, 如何订购
- powershell - 在调用 Get-Content 的结果上调用 Write-Host
- android - android菜单项不会出现在顶栏上
- javascript - 停止输入 React Js 时调用函数
- python - 空时如何让 QIntValidator() 调用editingFinished?
- python - For循环获取素数
- sql - SQL将值的总和分组为范围
- azure - 取消 Azure DevOps YML Pipelines 中的活动作业
- apache-tika - 如何使用 Apache Tika Server 从 PDF 中提取内联图像并将其保存为文件?
- powerbi - 如何在 Power Query 中添加重复的索引或排名列(1、1、2、2、3、3、4、4 等)