Validating Matching Strings [duplicate]
Asked Answered
A

3

23

When I use the Validation feature in Laravel, how can I add a pre-defined strings that are allowed in an Input?

For example, let's say I want the Input to contain only one of the following: foo,bar,baz, how can I do that?

$validator = Validator::make($credentials, [
      'profile' => 'required|max:255', // Here I want Predefined allowed values for it
]);
Aback answered 15/7, 2015 at 19:18 Comment(2)
Have you tried regex matching on the field for the words that you want to match ?Comnenus
Right now I am using the php in_array to manually check and throw excemption and havent tried the laravel validation regex. can you show a sample on that please?Aback
C
26

It is recommended in Laravel docs to put the validation rules in an array when they get bigger and I thought 3 rules were sufficient. I think it makes it for a more readable content but you do not have to. I added the regex portion below and I have it works. I am not that great with regexing stuff. Let me know.

$validator = Validator::make($credentials, [
      'profile' => ["required" , "max:255", "regex:(foo|bar|baz)"]  
]);
Comnenus answered 15/7, 2015 at 19:53 Comment(1)
Perfect! That worked! When the input doesnt match the regex, it throws the exception The profile format is invalid. I also removed the "max:255" since I am matching it with the regex anyways. Thank you so much @Comnenus This is exactly what I wanted! :)Aback
A
46

Best to use the 'in' validation rule like this:

$validator = Validator::make($credentials, [
      'profile' => ["required" , "max:255", "in:foo,bar,baz"]  
]);
Assessor answered 2/2, 2016 at 12:15 Comment(0)
C
26

It is recommended in Laravel docs to put the validation rules in an array when they get bigger and I thought 3 rules were sufficient. I think it makes it for a more readable content but you do not have to. I added the regex portion below and I have it works. I am not that great with regexing stuff. Let me know.

$validator = Validator::make($credentials, [
      'profile' => ["required" , "max:255", "regex:(foo|bar|baz)"]  
]);
Comnenus answered 15/7, 2015 at 19:53 Comment(1)
Perfect! That worked! When the input doesnt match the regex, it throws the exception The profile format is invalid. I also removed the "max:255" since I am matching it with the regex anyways. Thank you so much @Comnenus This is exactly what I wanted! :)Aback
C
0

Works for me in Laravel 9:

use Illuminate\Validation\Rule;
 
Validator::make($data, [
    'toppings' => [
        'required',
        Rule::notIn(['sprinkles', 'cherries']),
    ],
]);

Docs: https://laravel.com/docs/9.x/validation#rule-not-in

For the opposite you could use Rule::in(['foo', 'bar', 'baz'])

Crackup answered 2/1, 2023 at 9:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.