Laravel 自定义表单验证规则,验证过滤表情文字
1.定义验证规则,在创建文件app\Providers\Traits\ValidatorTrait.php
namespace App\Providers\Traits; use Illuminate\Support\Facades\Validator; trait ValidatorTrait { public function validatorBoot() { // 自定义字符串是否含有 Emoji 表情字符 Validator::extend('filterEmoji', function ($attribute, $value, $parameters, $validator) { return $this->checkEmoji($value); }); Validator::replacer('filterEmoji', function ($message, $attribute, $rule, $parameters) { return $message; }); } /** * 验证字段是否含有Emoje表情符号等. * @param $str * @return bool * @author code.cent123.com */ public static function checkEmoji($str) { $mbLen = mb_strlen($str); for ($i = 0; $i < $mbLen; ++$i) { $mbSubstr = mb_substr($str, $i, 1, 'utf-8'); if (strlen($mbSubstr) >= 4) { return false; } } return true; } }
2.在app\Providers\AppServiceProvider.php引入Trait
<?php namespace App\Providers; use Illuminate\Support\Facades\Schema; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Validator; class AppServiceProvider extends ServiceProvider { use \App\Providers\Traits\ValidatorTrait; /** * Register any application services. * * @return void */ public function register() { Schema::defaultStringLength(191); } /** * Bootstrap any application services. * * @return void */ public function boot() { //扩展验证规则 code.cent123.com $this->validatorBoot(); } }
3.语言文件resources\lang\zh-CN\validation.php 注意驼峰命名和下划线的转换
'filter_emoji' => ':attribute 含有不支持的字符',
4.测试
$validator = Validator::make($ary_data, [ 'status' => 'required', 'remarks' => 'required|between:5,100|filterEmoji', ], [ 'status.required' => '状态不能为空', ], [ 'remarks' => '审核意见', ]);