逃避Laravel验证规则 [英] escaping Laravel validation rules

查看:98
本文介绍了逃避Laravel验证规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户可配置的下拉列表,用户可以在其中使用自己的选项列表进行填充.我想使用in:foo,bar一种验证规则对其进行验证.

I have a user-configurable drop-down list where the user can populate it with their own list of options. I'd like to validate it with the in:foo,bar sort of validation rule.

不幸的是,这意味着有些人将输入诸如是的,我会的"之类的选项.如果我向验证规则传递一个下拉选项的内嵌列表,这显然会破坏验证.

Unfortunately, this means that some people are going to put in options like "Yes, I would". This is obviously going to break the validation if I pass an imploded list of drop-down options to the validation rule.

是否有可能避免Laravel的规则来避免此问题?

Is it possible to escape Laravel's rules to avoid this problem?

推荐答案

Validator类使用PHP的 str_getcsv()来解析规则的属性.该过程类似于:

The Validator class makes use of PHP's str_getcsv() to parse the attributes of a rule. The process goes something like:

  • 使用|管道定界符(Validator::explodeRules())
  • 展开所有规则
  • 使用:冒号分隔符(Validator::parseRule())
  • 分解规则名称和参数.
  • 通过str_getcsv()(Validator::parseParameters())发送属性
  • Explode all rules using the | pipe delimiter (Validator::explodeRules())
  • Explode the rule name and parameters using the : colon delimiter (Validator::parseRule())
  • Send the attributes through str_getcsv() (Validator::parseParameters())

这使您能够以与CSV文件相同的方式定义In:选项的列表-每一列都用引号引起来!这是一个示例:

This enables you to define your list of In: options the same way you would a CSV file -- with each column in quotes! Here's an example:

$input = ['foo' => 'Hello, world!'];

// Note the formatting of the `in:` options
$rules = ['foo' => 'required|in:"StackOverflow","Laravel","Hello, world!"',];

$v = Validator::make($input, $rules);

var_dump($v->passes()); // true

此外,请记住,与大多数Laravel一样,您可以以适合您的应用程序的任何方式扩展Validator类.如果您想要更强大的功能,则无需仅使用常规"现成的选项. :)

Also, remember that like most things Laravel, you can extend the Validator class in whatever way suits your application. If you want something more powerful, there's no need to stick with just the "stock" out-of-the-box options. :)

这篇关于逃避Laravel验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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