2 回答

TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
我建議兩種方法,第一種是使用 Laravel 的正則表達(dá)式規(guī)則。
$rules?=?[???????????? ??'songTime'?=>?['string',?'nullable',?'regex:/\d{1,2}:\d{1,2}/'] ];
您需要稍微修改正則表達(dá)式,這將接受一個(gè)或兩個(gè)數(shù)字、冒號(hào)和數(shù)字的任何模式。因此像 2:99 這樣的值將會(huì)被錯(cuò)誤地接受。
另一種選擇是編寫(xiě)自定義規(guī)則。這里的示例使用了閉包,但我強(qiáng)烈建議將其提取到自己的類中。
$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.');
? ? ? ? ? ? }
? ? ? ? },
? ? ],
];

TA貢獻(xiàn)1943條經(jīng)驗(yàn) 獲得超7個(gè)贊
使用 date_format 規(guī)則驗(yàn)證,如 H:i:s 或 i:s,您還可以使用表單驗(yàn)證請(qǐng)求,這將使您的代碼更小到控制器文件中。
<?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());
}
- 2 回答
- 0 關(guān)注
- 115 瀏覽
添加回答
舉報(bào)