Laravel 自定义表单验证规则,验证过滤表情文字

 Laravel  2021-05-26  admin  1733  2339

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' => '审核意见',
]);


如果文章对您有帮助,点击下方的广告,支持一下作者吧!

相关推荐


Systemd Web 管理系统:简化服务管理

# Systemd Web Systemd Web 是一个 Systemd 的 Web UI 管理系统,通过直观的界面和易用的操作,让用户能够轻松地管理 Linux 系统和服务。该项目旨在简化 Systemd 的使用,使得无论是专业的系统管理员还是普通的用户,都能够方便地对系统进行操作。 ## [github地址] (https://github.com/topascend/systemd

laravel 自定义写入日志

laravel 自定义写入日志if(!function_exists(&#39;myLog&#39;)){ /** *生成自定义文件日志内容 *@param$data *@paramstring$title *@parambool$isClear *@returnvoid *@Author:cent123.com */ functionmyLog($data,string$tit

systemctl 使用

Systemd是Linux系统工具,用来启动守护进程,已成为大多数发行版的标准配置。而systemctl是Systemd的主命令,用于管理系统。其实我们大部分服务都有使用systemctl管理,比如MySQL、Nginx等等。常见配置如下:[Unit] #单元描述 Description=GFAPP #在什么服务启动之后再执行本程序 After=mysql.service [Serv

封装 laravel 的公共队列,延迟处理任务

封装 laravel 的公共队列,延迟处理任务&lt;?php /** *ThisfileispartofLunanShopTeam. *http://code.cent123.com/ *@authorhttp://code.cent123.com/view/387 */ namespaceApp\Jobs; useException; useIlluminate\B