[英]how to add rule for time in laravel
I want to add a rule in laravel that is based on time type string.我想在 laravel 中添加一个基于时间类型字符串的规则。 User will send time of song like mm:ss sometime it will nullable and sometime it will send time of song 2:50.
用户会像mm:ss这样发送歌曲时间,有时它可以为空,有时它会发送歌曲时间 2:50。 I have added below code but i am unable to add time rule.
我添加了下面的代码,但我无法添加时间规则。
$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);
}
Two ways I would suggest, the first is to use Laravel's regex rule.我建议两种方法,第一种是使用 Laravel 的正则表达式规则。
$rules = [
'songTime' => ['string', 'nullable', 'regex:/\d{1,2}:\d{1,2}/']
];
You'd need to tinker with the regex a little, this will accept any pattern of one or two digits, a colon, and digits.您需要稍微修改一下正则表达式,这将接受任何一位或两位数字、冒号和数字的模式。 So something like 2:99 will be erroneously accepted.
所以像 2:99 这样的东西会被错误地接受。
The other alternative is to write acustom rule .另一种选择是编写自定义规则。 The example here is using a closure, but I'd highly recommend extracting it into its own class.
此处的示例使用了闭包,但我强烈建议将其提取到自己的 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.');
}
},
],
];
Use date_format rule validation like H:i:s or i:s, And also you can use form validation request that will make your code smaller into controller file.使用 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'
];
}
}
and in a controller file, you can use like this,在 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.