shieldforce / package-auto-validation-laravel
自动表单验证
dev-main
2021-02-05 16:59 UTC
Requires
- php: >=7.2.5
- laravel/framework: >=7.0
README
Laravel 自动验证包
此存储库包含自动验证包!
- 包链接
https://packagist.org.cn/packages/shieldforce/package-auto-validation-laravel
- 安装说明
composer require shieldforce/package-auto-validation-laravel
- 向 config/app.php 文件中添加 Provider
\ShieldForce\AutoValidation\Providers\AutoValidationServiceProvider::class,
- 在 Model 类中添加 Trait 和 Request
use ShieldForce\AutoValidation\Traits\TraitStartInterception;
use Illuminate\Http\Request;
- 在 Model 类中使用 Trait
use TraitStartInterception;
- 复制以下代码并将其粘贴到您的 Model 中(示例实现)
执行魔法的方法,您将在 boot 方法中验证的所有内容: (creating, created, saved, saving, updated, updating, retrieved, deleted, deleting, restored, restoring)
public static function rulesCustom(Request $request)
{
return
[
"request" => $request,
"creating" =>
[
"validations" =>
[
"first_name" => ["required", "string", "max:50"],
"last_name" => ["required", "string", "max:50"],
"email" => ["required", "string", "email", "max:100", "unique:users"],
"password" => ["required", "string", "min:4", "confirmed"],
],
"messages" =>
[
"first_name.required" => "Primeiro nome é obritatório",
"last_name.required" => ":attribute nome é obritatório",
]
],
"retrieved:login" =>
[
"validations" =>
[
"email" => ["required", "string", "email", "max:100"],
"password" => ["required", "string"],
],
"messages" =>
[
//
]
],
];
}
视图处理 - 在代码中的某处添加以下代码片段(请记住,需要 jQuery 和 Bootstrap 库才能完美运行)
{{-- Include Toast CSS and JS --}}
<link rel="stylesheet" href="/vendor/shieldforce/package-auto-validation-laravel/public/plugins/toast/toast.css">
<script src="/vendor/shieldforce/package-auto-validation-laravel/public/plugins/toast/toast.js"></script>
<script src="/vendor/shieldforce/package-auto-validation-laravel/public/js/toast.adapters.js"></script>
@if (count($errors) > 0)
<script>
$.toast( {
heading : 'Atenção ao(s) seguinte(s) erro(s):' ,
text : [
@foreach ($errors->all() as $error)
"{{ $error }}" ,
@endforeach
] ,
icon : 'error' ,
hideAfter : false ,
position : 'top-right' ,
} )
</script>
@endif
发布 JS 和 CSS 文件 - 运行命令
php artisan vendor:publish --tag=public --force
在验证错误返回的情况下,如果请求是通过 PHP 完成的,则返回如下
return back()
->with('errorValidation', 'Validação de Campos não passou!!')
->withErrors($validator)
->withInput()
->throwResponse();
在验证错误返回的情况下,如果请求是通过 JavaScript 完成的,则返回如下(在这种情况下,您将自行处理 AJAX 返回的错误等)
return response()->json([
'code' => 301,
'status' => "error",
'message' => "Validação de Campos não passou!!",
'data' => [
"errorValidation" => $validator->errors()
],
], 301)->throwResponse();
在 resources/lang/pt_BR/validation.php 文件中,我们可以配置返回消息,更改属性名称等...
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
// recaptcha - Guilherme Ferro
'recaptcha' => 'O campo :attribute não está correto.',
'accepted' => 'O :attribute deve ser aceito.',
'active_url' => 'O :attribute não é uma URL válida.',
'after' => 'O :attribute deve ser uma data depois :date.',
'alpha' => 'O :attribute só podem conter letras.',
'alpha_dash' => 'O :attribute só podem conter letras, números e traços.',
'alpha_num' => 'O :attribute só pode conter letras e números.',
'array' => 'O :attribute deve ser uma matriz.',
'before' => 'O :attribute deve ser uma data antes :date.',
'between' => [
'numeric' => 'O :attribute deve situar-se entre :min e :max.',
'file' => 'O :attribute deve situar-se entre :min e :max kilobytes.',
'string' => 'O :attribute deve situar-se entre :min e :max characters.',
'array' => 'O :attribute deve ter entre :min e :max itens.',
],
'boolean' => 'O :attribute campo deve ser verdadeira ou falsa.',
'confirmed' => 'O :attribute confirmação não corresponde.',
'date' => 'O :attribute não é uma data válida.',
'date_format' => 'O :attribute não coincide com o formato :format.',
'different' => 'O :attribute e :other deve ser diferente.',
'digits' => 'O :attribute deve ser :digits dígitos.',
'digits_between' => 'O :attribute deve situar-se entre :min e :max dígitos.',
'dimensions' => 'O :attribute tem dimensões de imagem inválidos.',
'distinct' => 'O :attribute campo tem um valor duplicado.',
'email' => 'O :attribute deve ser um endereço de e-mail válido.',
'exists' => 'O selecionado :attribute é inválido.',
'filled' => 'O :attribute campo é obrigatório.',
'image' => 'O :attribute deve ser uma imagem.',
'in' => 'O selecionado :attribute é inválido.',
'in_array' => 'O :attribute campo não existe no :other.',
'integer' => 'O :attribute deve ser um número inteiro.',
'ip' => 'O :attribute deve ser um endereço IP válido.',
'json' => 'O :attribute deve ser uma cadeia JSON válido.',
'max' => [
'numeric' => 'O :attribute não pode ser superior a :max.',
'file' => 'O :attribute não pode ser superior a :max kilobytes.',
'string' => 'O :attribute não pode ser superior a :max characters.',
'array' => 'O :attribute não pode ter mais de :max itens.',
],
'mimes' => 'O :attribute deve ser um arquivo do tipo: :values.',
'min' => [
'numeric' => 'O :attribute deve ser de pelo menos :min.',
'file' => 'O :attribute deve ser de pelo menos :min kilobytes.',
'string' => 'O :attribute deve ser de pelo menos :min characters.',
'array' => 'O :attribute deve ter pelo menos :min itens.',
],
'not_in' => 'O selecionado :attribute é inválido.',
'numeric' => 'O :attribute deve ser um número.',
'present' => 'O campo :attribute deve estar presente.',
'regex' => 'O :attribute formato é inválido.',
'required' => 'O campo :attribute é necessário.',
'required_if' => 'O campo :attribute é necessária quando :other é :value.',
'required_unless' => 'O campo :attribute é necessária a menos :other é in :values.',
'required_with' => 'O campo :attribute é necessária quando :values é present.',
'required_with_all' => 'O campo :attribute é necessária quando :values é present.',
'required_without' => 'O campo :attribute é necessária quando :values não está presente.',
'required_without_all' => 'O campo :attribute é requerido quando nenhum :values estão presentes.',
'same' => 'O :attribute e :other devem corresponder.',
'size' => [
'numeric' => 'O :attribute deve ser :size.',
'file' => 'O :attribute deve ser :size kilobytes.',
'string' => 'O :attribute deve ser :size characters.',
'array' => 'O :attribute deve conter :size itens.',
],
'string' => 'O :attribute deve ser uma string.',
'timezone' => 'O :attribute deve ser uma zona válida.',
'unique' => 'Este :attribute já foi registrado.',
'url' => 'O :attribute formato é inválido.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
'first_name' => [
'required' => 'Campo :attribute é obrigatório',
'integer' => 'Campo :attribute deve ser um inteiro',
'min' => 'Campo :attribute deve conter a data mínima de 2000',
'max' => 'Campo :attribute deve conter a data máxima de 2050',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => [
'g-recaptcha-response' => 'reCAPTCHA',
'first_name' => 'Primeiro Nome:',
],
];
- 例外 - 如果不想验证特定的请求,请在请求中传递
$request["not_validation"] === "yes";
团队
Alexandre Ferreira do Nascimento
许可证
许可证所有者:owner .