如何在 laravel 中添加时间规则

how to add rule for time in laravel

我想在 laravel 中添加一个基于时间类型字符串的规则。用户将发送歌曲时间,如 mm:ss,有时它可以为空,有时它会发送歌曲时间 2:50。我添加了以下代码,但我无法添加时间规则。

    $data = request(['songTime']);
$rules = [            
            'songTime' => 'string|nullable|MM:SS'
        ];

        $validator = Validator::make($data, $rules);
        if ($validator->fails() ) {
            return response()->json([
                'message' => 'Invalid Request',
                'error' => $validator->messages()
            ], 400);
        }

我建议两种方法,第一种是使用 Laravel 的 regex 规则。

$rules = [            
  'songTime' => ['string', 'nullable', 'regex:/\d{1,2}:\d{1,2}/']
];

您需要稍微修改正则表达式,这将接受一个或两个数字、冒号和数字的任何模式。所以像 2:99 这样的东西会被错误地接受。

另一种方法是写一个custom rule。这里的示例使用闭包,但我强烈建议将其提取到自己的 class.

$rules = [
    'songTime' => [
        'string',
        'nullable',
        static function ($attribute, $value, $fail) {
            [$min, $sec] = explode(':', $value);

            if (ctype_digit($min) === false || ctype_digit($sec) === false || $sec > 59) {
                $fail($attribute . ' is invalid.');
            }
        },
    ],
];

使用 date_format 规则验证,例如 H:i:s 或 i:s,您也可以使用表单验证请求,这将使您的代码更小到控制器文件中。

<?php
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ValidateSongTimeRequest 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 [
         'songTime' => 'required|date_format:H:i:s'
    ];
}
}

在控制器文件中,你可以这样使用,

public function validateTime(ValidateSongTimeRequest $request) {
    $inputs = $request->all();
    try {
        
    } catch (Exception $exception) {
        Log::error($exception);
    }
 throw new Exception('Error occured'.$exception->getMessage());
}