Laravel 5.2 验证检查值是否不等于变量
Laravel 5.2 validation check if value is not equal to a variable
在我的例子中,一个用户正在邀请另一个用户,我想检查他们邀请的用户是否不是他们自己。
因此我有两个变量 incomming email 和 user->email
$this->validate($request, [
'email' => 'required|email',
]);
如何将该验证规则添加到验证调用中?
您可以使用 not_in
,它允许您指定要拒绝的值列表:
$this->validate($request, [
'email' => 'required|email|not_in:'.$user->email,
]);
可以根据laravel Document
使用different:field
例如在您的请求验证中:
public function rules()
{
return [
'from' => 'required',
'to' => 'required|different:from',
'action' => 'required',
'access' => 'required'
];
}
这两个from
和to
应该是不同的(不一样)。
正如@Vlad Barseghyan 在接受的答案中提到的那样:
The case is that if from will be from='3' and to=3, they will considered as different.
这是因为 different
验证规则比较给定字段的方式。它使用严格的比较,在处理 integers
.
时在某些情况下会导致意外行为
not_in
规则使用松散比较,可用于完成与 different
规则相同的行为。
public function rules()
{
return [
'from' => 'required',
'to' => 'required|not_in:' . $this->from,
'action' => 'required',
'access' => 'required'
];
}
public function messages()
{
return [
'to.not_in' =>
'to and from should be different.'
];
}
在我的例子中,一个用户正在邀请另一个用户,我想检查他们邀请的用户是否不是他们自己。
因此我有两个变量 incomming email 和 user->email
$this->validate($request, [
'email' => 'required|email',
]);
如何将该验证规则添加到验证调用中?
您可以使用 not_in
,它允许您指定要拒绝的值列表:
$this->validate($request, [
'email' => 'required|email|not_in:'.$user->email,
]);
可以根据laravel Document
使用different:field
例如在您的请求验证中:
public function rules()
{
return [
'from' => 'required',
'to' => 'required|different:from',
'action' => 'required',
'access' => 'required'
];
}
这两个from
和to
应该是不同的(不一样)。
正如@Vlad Barseghyan 在接受的答案中提到的那样:
The case is that if from will be from='3' and to=3, they will considered as different.
这是因为 different
验证规则比较给定字段的方式。它使用严格的比较,在处理 integers
.
not_in
规则使用松散比较,可用于完成与 different
规则相同的行为。
public function rules()
{
return [
'from' => 'required',
'to' => 'required|not_in:' . $this->from,
'action' => 'required',
'access' => 'required'
];
}
public function messages()
{
return [
'to.not_in' =>
'to and from should be different.'
];
}