代码之家  ›  专栏  ›  技术社区  ›  Udders

laravel验证由3个输入组成的日期

  •  0
  • Udders  · 技术社区  · 6 年前

    <input name="day" type="text" />
    <input name="month" type="text" />
    <input name="year" type="text" />
    

    我验证每个单独的输入,但是我需要验证如果他们在所有3个字段中都输入了数据(day和month是可选的),日期是过去的而不是将来的,这是我当前的请求类,

    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 回复  |  直到 6 年前
        1
  •  0
  •   justrusty    6 年前

    您可以使用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
    }
    
    推荐文章