I need to validate a string whose length is exactly 6 OR 8. How could I make the rule for this validation?
The number must be 6 OR 8, it cannot be between 6 and 8.
I need to validate a string whose length is exactly 6 OR 8. How could I make the rule for this validation?
The number must be 6 OR 8, it cannot be between 6 and 8.
3
Answers
You need to create a custom rule.
In the sample below, I used the Closure to create a custom rule, but you can create a rule object to reuse it.
I used the
mb_strlen
instead ofstrlen
to cover multibyte. (UTF8 chars)Try saving string length first and then check with if conditions.
or use regex validation rule for length as:
For string length.
You don’t actually need to make your own validator, since Laravel’s validation comes with a regex validation rule, so you could just do:
Regex stolen and adapted from here but you can test it here
Regex Explanation:
OLD ANSWER (unnecessarily complicated)
Regex Explanation: