'regex:/-6ren">
gpt4 book ai didi

Laravel 验证字段必须有 4 个字

转载 作者:行者123 更新时间:2023-12-03 23:05:56 25 4
gpt4 key购买 nike

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

  • “安迪 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com