[英]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 的正則表達式規則。
$rules = [
'songTime' => ['string', 'nullable', 'regex:/\d{1,2}:\d{1,2}/']
];
您需要稍微修改一下正則表達式,這將接受任何一位或兩位數字、冒號和數字的模式。 所以像 2:99 這樣的東西會被錯誤地接受。
另一種選擇是編寫自定義規則。 此處的示例使用了閉包,但我強烈建議將其提取到自己的 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,您還可以使用表單驗證請求,使您的代碼更小到 controller 文件中。
<?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'
];
}
}
在 controller 文件中,您可以這樣使用,
public function validateTime(ValidateSongTimeRequest $request) {
$inputs = $request->all();
try {
} catch (Exception $exception) {
Log::error($exception);
}
throw new Exception('Error occured'.$exception->getMessage());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.