Laravel验证字段必须有4个字
我想让字段名写在一个四边形中 同样的Laravel验证字段必须有4个字,laravel,Laravel,我想让字段名写在一个四边形中 同样的 “andy hosam rami entaida” 或 “سرررمممرمممووى” 托盘 'name' => 'regex:/^[\wء-ي]+\s[\wء-ي]+\s[\wء-ي]+\s[\wء-ي]+/ 在英语中,阿拉伯语中的所有true都是false regex是真的我测试它听到regexr.com/57s61 我可以用另一种方式使用php,那么如何用laravel编写呢 if(count(explode('
- “andy hosam rami entaida” 或
- “سرررمممرمممووى”
'name' => 'regex:/^[\wء-ي]+\s[\wء-ي]+\s[\wء-ي]+\s[\wء-ي]+/
在英语中,阿拉伯语中的所有true都是false
regex是真的我测试它听到regexr.com/57s61
我可以用另一种方式使用php,那么如何用laravel编写呢
if(count(explode(' ',$name)) < 4)
{
$error[] ='enter full name with 4 words';
}
if(计数(分解(“”,$name))<4)
{
$error[]=“用4个单词输入全名”;
}
您可以创建一个自定义类,以封装的方式进行自定义验证
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)],
];
}
您是否也需要支持错误消息的多种语言的解决方案?如果是这样,我将修改我的解决方案,并将其添加到您的问题中。