A rule to validate delimited data
laravel-validation-rules is a package that contains handy custom validation rules that are being used in various client projects we made at Spatie. Last week I added a new validate rule called Delimited
to the package.
In this blog post, I'd like to explain why we added it and how it can be used.
Do you really need multi-value inputs?
Last week Caleb "String King" Porzio tweeted this:
Let's all just take a minute to appreciate the beauty of this text field from @pushsilver (@davidhemphill)
— Caleb Porzio (@calebporzio) May 14, 2019
A simple text field for multiple items. No select2, no vue-select, no custom multi-input thingy with an "add" button.
Just a lil bit of simple parsing on the backend. ? pic.twitter.com/xPvljsVXqr
I think he's right. Why bother to go through all the hassle creating a multi-input thing, when accepting a delimited string is good enough.
In a project I'm working on, there are some fields that accept multiple email-addresses and other fields that accept multiple phone numbers. I decided to let them be input as comma separated strings. The first thing that was needed is validation.
Introducing the Delimited
rule
To validate both comma separated emails and comma separated phone number, I created a new validation rule named Delimited
that can validate all kinds of validated data. It's meant to be used in a form request. Its constructor accepts a validation rule that will be used to validate each item in the delimited string.
Here's an example of its usage:
// in a `FormRequest`
public function rules()
{
return [
'emails' => [new Delimited('email')],
];
}
Here's some example input that passes this rule:
-
'sebastian@example.com, alex@example.com'
-
''
-
'sebastian@example.com'
-
'sebastian@example.com, alex@example.com, brent@example.com'
-
' sebastian@example.com , alex@example.com , brent@example.com '
This input will not pass:
-
'@example.com'
-
'nocomma@example.com nocommatoo@example.com'
-
'valid@example.com, invalid@'
If you need to validate a comma-separated string with phone numbers, you can simple pass the phone
rule to Delimited
.
// in a `FormRequest`
public function rules()
{
return [
'phone_numbers' => [new Delimited('phone')],
];
}
How to process the validated delimited data is up to you. You could save the validated delimited string to the database. Or you could explode
the value and save it as an array in the db. The choice is up to you.
In closing
The Delimited
Rule has many other options. You can set a minimum and maximum of items, use another delimiter, accept duplications, disable trimming, ... Take a look at the readme of the laravel-validation package to learn more about these options.
What are your thoughts on "A rule to validate delimited data"?