编程

Laravel 中你可能不知道的十大验证规则

180 2024-10-03 10:33:00

你了解 Laravel 中所有的验证规则吗?再想想!Laravel 有很多现成的验证规则,可以让你的代码生活变得更容易。让我们来看看你可能不知道存在的前 10 条验证规则。

1. Prohibited

要确保某个字段不存在于输入中,请使用 prohibited

'username' => 'prohibited',

如果 username 存在于请求中,验证会失败。简单且有效,特别对于蜜罐。

2. Prohibits

需要一个字段来禁止另一个字段出现吗?看看这个。

'password' => 'prohibits:username',

如果 password 存在,则 username 一定不能存在。

3. Required If

当你需要条件验证时,这是一个救星。

'email' => 'required_if:contact_method,email',

只有当 contact_method 值为 email 时,email 字段才是必需的。

4. Required Unless

required_if 相反,除非另一个字段有某个指定值,否则该字段是必需的。to require a field unless another field has a specific value.

'email' => 'required_unless:contact_method,phone',

email 除非 contact_method 的值为 phone,否则 email 字段是必需的

5. Required Without

只有当另一个字段不存在时,该字段才是必需的。

'email' => 'required_without:phone',

如果未能提供 phone 字段,则必需有  email 字段。

6. Required Without All

如果其他字段都不存在,此字段才是必需的。

'email' => 'required_without_all:phone,address',

如果 phoneaddress 都不存在,则 email 是必需的。

7. Starts With

检测字符串是否以给定的值开头:

'username' => 'starts_with:admin,user',

username 必需以 adminuser 开头。

8. Ends With

类似地,检测字符串是否以给定的值结尾

'username' => 'ends_with:_admin,_user',

username 必需以 _admin_user 开头。

9. In Array

确认一个字段的值存在于另一个数组字段中。

'selected_option' => 'in_array:available_options.*',

selected_option 字段的值必需 available_options 数组中存在。

10. Different

确保两个字段的值是不同的。

'new_password' => 'different:current_password',

new_password 字段的值必需与current_password 的值不一样。

总结

本文总结了你可能不知道的十个超级方便的 Laravel 验证规则。使用它们可以节省你的时间,使代码更清晰、更高效。