Laravel 验证字段必须有 4 个字

标签 laravel

我想让字段名称写成四边形
相同的

  • “安迪 hosam rami entaida”
  • "حسام احمد محمد متولى"

  • 我托盘
                'name' => 'regex:/^[\wء-ي]+\s[\wء-ي]+\s[\wء-ي]+\s[\wء-ي]+/
    
    在英语中,所有真实的阿拉伯语都是错误的
    regex 是真的我测试它听到 regexr.com/57s61
    我可以用另一种方式使用 php,那么如何用 laravel 编写呢?
    if(count(explode(' ',$name)) < 4)
      {
         $error[] ='enter full name with 4 words';
      }
    

    最佳答案

    您可以定制 Rule类以封装的方式进行自定义验证。

    namespace App\Rules;
    
    use Illuminate\Contracts\Validation\Rule;
    
    class NumWords implements Rule
    {
        private $attribute;
        private $expected;
        
        public function __construct(int $expected)
        {
            $this->expected = $expected;
        }
    
        /**
         * Determine if the validation rule passes.
         *
         * @param  string  $attribute
         * @param  mixed  $value
         * @return bool
         */
        public function passes($attribute, $value)
        {
            $this->attribute = $attribute;
            $trimmed = trim($value);
            $numWords = count(explode(' ', $trimmed));
            return $numWords === $this->expected;
        }
    
        /**
         * Get the validation error message.
         *
         * @return string
         */
        public function message()
        {
            return 'The '.$this->attribute.' field must have exactly '.$this->expected.'  words';
        }
    }
    
    
    然后您可以在验证中的任何地方使用它,如下所示:
        public function rules()
        {
            return [
                'name' => [ 'required', 'string', new NumWords(4)],
            ];
        }
    

    关于Laravel 验证字段必须有 4 个字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62736720/

    相关文章:

    mysql - Laravel 使用 Like 运算符和 '%"通过原始查询添加参数

    php - 如何使用Laravel实现微服务和API网关之间的认证和授权

    Laravel 按 Eloquent 关系分组

    php - Laravel 网站上的分页重定向到主页

    laravel - 在 Laravel Blade + Vite 中使用 Vue3 组件

    mysql - 检查我的数据库关系结构是否正确

    javascript - 如何在没有 'onchange' 的下拉列表中显示预选值

    php - 从逗号分隔中查找匹配的关键字

    performance - Laravel 用于复杂的浏览器游戏网站

    php - 使用 cURL 获取 JSON 响应