Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Validation Not Working For Multi-byte Characters

Tags:

php

laravel

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

like image 844
eylay Avatar asked Jul 16 '20 07:07

eylay


1 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)

like image 89
apokryfos Avatar answered Oct 14 '22 05:10

apokryfos