douna6802 2017-02-08 14:33
浏览 110
已采纳

使用2个字段的Laravel表单验证是唯一的

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

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. 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

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

Any hint?

  • 写回答

4条回答 默认 最新

  • douxia9826 2017-02-08 14:43
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程