php - laravel 验证由 3 个输入组成的日期
问题描述
在我正在构建的网站上,我以 3 种不同的输入向用户询问他们的出生日期,
<input name="day" type="text" />
<input name="month" type="text" />
<input name="year" type="text" />
我验证每个单独的输入,但我需要验证他们是否在所有 3 个字段(日和月是可选的)中输入了数据,日期是过去而不是未来,这是我目前的请求类,
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'firstnames' => 'required',
'lastname' => 'required',
'dob_day' => 'digits_between:1,2|nullable|between:1,31',
'dob_month' => 'digits_between:1,2|nullable|between:1,12',
'dob_year' => 'digits:4|required',
//need to validate the date of birth if all 3 have values.
];
}
/**
* Get the validation messages that apply to the rules
*
* @return array
*/
public function messages()
{
return [
'firstnames.required' => 'Please enter any first names',
'lastname.required' => 'Please enter a last name',
//'birth_place.required' => 'Please enter a place of birth',
'dob_month.digits_between' => 'The date of birth\'s month must be no more than 2 characters in length',
'dob_day.digits_between' => 'The date of birth\'s day must be no more than 2 characters in length',
'dob_month.max' => 'The date of birth\'s month must be no more than 2 characters in length',
'dob_year.digits' => 'The date of birth\'s year must be 4 characters in length',
'dob_year.required' => 'Please enter a year of birth, even if it is an estimate',
//'dob_accurate.required' => 'Please specify whether the date of birth is accurate'
];
}
如果日期作为过去的日期无效,我是否可以将三个不同的输入验证为 1 并抛出错误?
解决方案
您可以使用 javascript 将日期设置到另一个隐藏字段中,如果其他字段已填写,您可以像过去一样验证该字段。或者,如果您不想使用 javascript,您可以在当前日期输入的 if 语句中进行一些额外检查,并更改其规则以适应或抛出异常
public function rules()
{
$rules = [
'firstnames' => 'required',
'lastname' => 'required',
'dob_day' => ['digits_between:1,2', 'nullable', 'between:1,31'],
'dob_month' => ['digits_between:1,2', 'nullable', 'between:1,12'],
'dob_year' => ['digits:4', 'required']
//need to validate the date of birth if all 3 have values.
];
if (request()->has('dob_day')&&request()->has('dob_month')&&request()->has('dob_year')) {
$date = now();
$rules['full_date'] = 'before:'.now()->toDateString();
//Or if you don't want to use javascript you can do some extra checking here on the current date inputs and change their rules to fit or throw an exception
$rules['dob_year'][] = 'max:'.now()->year;
...
}
return $rules
}
推荐阅读
- reactjs - 如果其他条件无法正常工作,则反应
- ios - 从情节提要的 UICollectionViewFlowLayout 创建 IBOutlet 时出错
- javascript - JQuery ajax 函数发送正确的值。但 RestController 收到 null
- ruby-on-rails - 使用错误的 ruby 版本运行的 bundle 命令
- typescript - rxjs在内部映射switchMap时需要联合类型
- android - 第一次执行后如何停止排队的调用?
- assembly - 如何从数据表中使 PIC18F4520 启动 RTC 中断
- dart - 呈现下一部分项目时,无限的 CustomScrollView 会向后滚动
- c# - Newtonsoft 反序列化相同的日期返回不同的输出
- git - 仅使用一些文件在版本控制中创建标签//分支