我想让字段名称写成四边形
相同的
或
我托盘
'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/