首页 > 解决方案 > 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 并抛出错误?

标签: phplaraveldate

解决方案


您可以使用 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
}

推荐阅读