|string> */ public function rules(): array { return [ 'content' => ['nullable', 'required_without:image', 'string', 'max:500'], // 文本与图片至少二选一 'image' => ['nullable', 'required_without:content', 'file', 'image', 'mimes:jpeg,png,jpg,gif,webp', 'max:6144'], 'to_user' => ['nullable', 'string', 'max:50'], 'is_secret' => ['nullable', 'boolean'], 'font_color' => ['nullable', 'string', 'max:10'], // html color hex 'action' => ['nullable', 'string', 'max:50'], // 动作(例如:微笑着说) ]; } /** * 返回校验失败时的中文提示。 */ public function messages(): array { return [ 'content.required_without' => '文字内容和图片至少要发送一项。', 'content.max' => '发言内容不能超过 500 个字符。', 'image.required_without' => '文字内容和图片至少要发送一项。', 'image.image' => '上传的文件必须是图片。', 'image.mimes' => '仅支持 jpg、jpeg、png、gif、webp 图片格式。', 'image.max' => '图片大小不能超过 6MB。', ]; } /** * 重写验证失败的处理,无论如何(就算未按 ajax 标准提交)都必须抛出 JSON,不可以触发网页重定向去走 GET 请求而引发 302 方法错误 */ protected function failedValidation(Validator $validator): void { throw new HttpResponseException(response()->json([ 'status' => 'error', 'message' => $validator->errors()->first(), 'errors' => $validator->errors(), ], 422)); } }