Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
184 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

  • 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())

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...