gpt4 book ai didi

laravel - "Not"验证规则中的运算符

转载 作者:行者123 更新时间:2023-12-02 08:28:19 24 4
gpt4 key购买 nike

我有一个自定义验证规则 is_admin,用于检查用户是否是管理员。

Laravel 是否有一个“相反”运算符(就像 ! 在 PHP 中的工作方式一样),这样我就可以执行类似 not:is_admin 的操作,这将检查用户不是管理员:

$rules = array(
'user_id' => 'required|numeric|not:is_admin'
);

$validator = Validator::make(Input::all(), $rules);

if ($validator->fails())
{
// return error
}
else
{
// continue
}

谢谢。

最佳答案

是的,我们可以通过在规则数组上使用条件语句。

$rules 是一个数组,我们传递给验证类或在 Request 类中定义。

示例#1:

public function rules{
//here we return an array of rules like shown below.
return [
'field_a' => 'required',
'field_b' => 'required',
];
//we can add any operator by a little change.
save validation rules array in variable like shown below.
$rules = [
'field_a' => 'required',
'field_b' => 'required',
];

//now we can add any rule in $rules array using common ways of writing conditional statements.

//For example field_c is required only when field_a is present and field_b is not
if(isset($this->field_a) && !isset($this->field_b)){
$rules['field_c' => 'required'];
}
//we can apply any kind of conditional statement and add or remove validation rules on the basis of our business logic.
}

示例#2

public function rules(){

$rules = [];

if ($this->attributes->has('some-key')) {
$rules['other-key'] = 'required|unique|etc';
}

if ($this->attributes->get('some-key') == 'some-value') {
$rules['my-key'] = 'in:a,b,c';
}

if ($this->attributes->get('some-key') == 'some-value') {
$this->attributes->set('key', 'value');
}

return $rules;
}

关于laravel - "Not"验证规则中的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31527217/

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