I have a form and there is a field in this form called dimensions
and users MUST enter a value like this: 10x10x10
So I am separating length, width and height by x
.
But now I don’t know how to make this validation with Laravel:
$request->validate([ 'dimensions' => 'required|max:10|min:5', ]);
So the question is: How can I force users to separate each dimensions by writing x
?
Advertisement
Answer
You can use the regex
validation rule. You’d provide it with a pattern
that matches your requirements (10x10x10
in your case).
Something like the following:
'dimensions' = ['required', 'regex:/^([d]+x){2}([d]+)$/']
You might want to constrain the number of digits it allows to prevent daft input. The +
after [d]
is greedy and will match digits an unlimited number of times.
'dimensions' = ['required', 'regex:/^([d]{1,5}x){2}([d]{1,5})$/']
The above pattern constrains the number of digits allowed the a minimum of 1 and maximum of 5 ({1,5}
) rather than unlimited (+
).
There is probably a neater pattern
that someone might suggest.