Laravel Validation Not Working For Multi-byte Characters

Viewed 1451

I have an input where user enters his work shop code, and work shop code must be 10 digits. So in my validation I have :

$apply_data = $request->validate([
   'workshop_name' => 'required|string',
   'workshop_code' => 'required|string|digits:10',
]);

Now when user enters 1231231231 its ok. but if user enters ١٢٣١٢٣١٢٣١ (10 Arabic numbers instead of English numbers) Laravel will return following error

work shop code must be 10 digits

I guess laravel is using strlen rather than mb_strlen, because workshop is actually 10 digits.

How can I fix this?

UPDATE Laravel is actually using strlen rather than mb_strlen https://github.com/laravel/framework/blob/41ea7cc3bb898ff86505d3798d8acbb8992a0aad/src/Illuminate/Validation/Concerns/ValidatesAttributes.php#L414

2 Answers

As per my comment, you can achieve this by using the regex to determine the input is 10 unicode numbers like below:

$apply_data = $request->validate([
   'workshop_name' => 'required|string',
   'workshop_code' => [ 'required', 'string', 'regex:/^\p{N}{10}$/u' ],
], [ 
   'regex' => 'Workshop code must consist of 10 numbers'
]);

\p{N} means a unicode character having the property N (number)

First of Laravel must fix their code in order to support multi-byte characters. but for now we can use size instead of digits

$apply_data = $request->validate([
   'workshop_name' => 'required|string',
   'workshop_code' => 'required|string|size:10',
]);

laravel size validation uses mb_strlen()

Related