Laravel表单验证使用2个字段是唯一的 [英] Laravel form validation unique using 2 fields

查看:579
本文介绍了Laravel表单验证使用2个字段是唯一的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在2个字段上有唯一的验证规则?

How can I have a unique validation rule on 2 fields?

a.该应用程序不应允许两个人具有相同的名字和姓氏.

a. The application should not allow two people to have the same identical first name and last name.

允许用户仅填写名字或姓氏.因为用户可能只有其中之一.

It is allowed that the users fills in only a first name or only a last name. Because the user may have only one of them.

b.但是,如果用户仅输入名字(Glen),则表中的其他任何人都不应具有相同的名字(名字='Glen',姓氏=空).另一个格伦·史密斯"好吧.

b. But if the user enters only a first name (Glen), no other person in the table should have the same (first name = 'Glen' and last name = null). another 'Glen Smith' ok.

我尝试了以下规则.当两个字段(名字和姓氏)都不为空时,它会很好地工作:

I tried the following rule. It works great when both fields (first and last name) are not null:

'firstName' => 'unique:people,firstName,NULL,id,lastName,' . $request->lastName

此规则在b上失败.当只有一个字段时.

This rule fails on b. when only one field is present.

有任何提示吗?

推荐答案

内置的unique验证程序实际上并不支持您要执行的操作.目的是确保单个有效值在数据库中是唯一的,而不是两个值的组合.但是,您可以创建自定义验证器:

The built in unique validator wouldn't really support what you're trying to do. It's purpose is to ensure that a single valid is unique in the database, rather than a composite of two values. However, you can create a custom validator:

Validator::extend('uniqueFirstAndLastName', function ($attribute, $value, $parameters, $validator) {
    $count = DB::table('people')->where('firstName', $value)
                                ->where('lastName', $parameters[0])
                                ->count();

    return $count === 0;
});

然后您可以通过以下方式访问此新规则:

You could then access this new rule with:

'firstName' => "uniqueFirstAndLastName:{$request->lastName}"

您可能会发现您可能需要对数据库查询进行一些调整,因为它未经测试.

You'll probably find you might need to tweak your database query a little bit as it's untested.

这篇关于Laravel表单验证使用2个字段是唯一的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆