Skip to content

Commit

Permalink
🔧: 表单验证
Browse files Browse the repository at this point in the history
  • Loading branch information
Joycezhangw committed Sep 16, 2022
1 parent 2aafc08 commit fbfe238
Show file tree
Hide file tree
Showing 2 changed files with 114 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/Validation/BaseRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php


namespace JoyceZ\LaravelLib\Validation;


use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

/**
* 表单提交验证
* Class BaseRequest
* @package JoyceZ\LaravelLib\Validation
*/
abstract class BaseRequest extends FormRequest
{
/**
* 定义验证规则
* @return array
*/
public function rules()
{
$rule_action = 'getRulesBy' . ucfirst($this->route()->getActionMethod());

if (method_exists($this, $rule_action))
return $this->$rule_action();

return $this->getDefaultRules();
}

/**
* 默认验证规则
* @return array
*/
protected function getDefaultRules()
{
return [];
}

/**
* 验证消息通过,json抛出,api开发
* @param Validator $validator
* @throws \HttpResponseException
*/
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json([
'code' => -1,
'message' => $validator->errors()->first()
]));
}
}
61 changes: 61 additions & 0 deletions src/resources/stubs/request.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

namespace $NAMESPACE$;

use JoyceZ\LaravelLib\Validation\BaseRequest;

/**
* 请说明具体哪块业务的 Request
*
* Class $CLASS$Request
* @package $NAMESPACE$
*/
class $CLASS$Request extends BaseRequest
{

/**
* 定义针对 Controller->store( )的验证规则
* @return array
*/
public function getRulesByStore()
{
return [

];
}

/**
* 定义针对 Controller->update( )的验证规则
* @return array
*/
public function getRulesByUpdate()
{
return [

];
}

/**
* 定义针对 Controller->delete( )的验证规则
*
* @return array
*/
public function getRulesByDelete()
{
return [
];
}

/**
* 统一定义验证规则的自定义错误消息。
* @return array
*/
public function messages()
{
return [

];
}


}

0 comments on commit fbfe238

Please sign in to comment.