Reputation: 551
How to validate numbers using laravel validator. In my case I need to validate if a number is between "1.00" and "50.00".
As seperator between the number pairs the "." and the "," should be allowed. The number should have only two decimal places. Is there a way to get this done using standart laravel validators combined?
using a regex, the regex should match these requirements:
starting with 0-9 (2 numbers are possible)
followed by one . or one ,
followed with 0-9 (2 numbers are possible)
OR simple numbers like 1-9 with NO dots and NO commas
numbers between 1 and 50 should be allowed in total. This regex should be used for a prepaid system where users should be able to topup their accounts from 1 to 50. For this reason entries like 1.00 and 1,00 should be valid as well as 1 or 2. 50.00 is the maximum of amount. 1.00 the minimum.
Upvotes: 1
Views: 217
Reputation: 3207
This is the regex you are lookig for:
/^((([1-4][0-9]|[1-9])([,.]\d{1,2})?)|(?:50([,.]0{1,2})?))$/
Upvotes: 2
Reputation: 3207
You can use regular expresions like this:
$rules = [
'field' => 'regex:/^\d*(\.\d{2})?$/'
];
PS: This tool could be useful https://regex101.com/
Upvotes: 1
Reputation: 111829
I would create the following Request class:
<?php
namespace App\Http\Requests;
class TestRequest extends Request
{
public function rules()
{
return [
'number' => [
'required',
'regex:/^\d{1,2}(\.\d{1,2})?$/',
'numeric',
'min:1',
'max:50'
],
];
}
public function authorize() {
return true;
}
public function all() {
$data = parent::all();
if (isset($data['number'])) {
$data['number'] = str_replace(',','.', $data['number']);
}
return $data;
}
}
and in Controller inject this Request class:
public function test(TestRequest $request)
{
dd($request->all());
}
Upvotes: 1