Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Input validation Between is not validate correctly

currently i'm facing some issue in laravel input validation where the validation rules for between seems like doesnt apply correctly. Below is my HTML code.

<input type="hidden" name="_token" value="{{ csrf_token() }}">
                <div class="margin-bottom-10">
                    <label>Thread Title :</label>
                    <input name="thread_title" maxlength="100" required>
                </div>                  
                <div class="margin-bottom-10">
                    <label>Price :</label>
                    <input type="number" step="0.01" min="0" required title="Please enter price with x.xx format." name="thread_item_price" />
                </div>

What i'm trying to do is to validate the given price must be between 0 and 9999.99. I inspect element and remove the min="0" and try to submit with negative value says -1000, the system seems to accept the input. Below is my validator rules

$validator = Validator::make($request::all(),
            [
                'thread_title' => 'required|max:100',
                'thread_item_price' => 'between:0,9999.99'
            ],
            [
                'thread_title.required' => 'Please fill in thread title.',
                'thread_title.max' => 'Thread title has exceeded 100 characters.',
                'thread_item_price.required' => 'Price cannot be empty.',
                'thread_item_price.between' => 'Price must be equals to 0 or 9999.99.',
            ]);

        if ($validator->fails()) {
            return Redirect::back()
                ->withErrors($validator)
                ->withInput();
        };

Am i doing something wrong and make the validation failed?

like image 254
Darren Lau Avatar asked Oct 29 '15 14:10

Darren Lau


2 Answers

You need to let Laravel know that it's a numeric value. This should work for you.

'thread_item_price' => 'numeric|between:0,9999.99'
like image 113
Thomas Kim Avatar answered Oct 10 '22 20:10

Thomas Kim


Between rule accept only integers for numerics. You should use digits_between rule for float numbers.

Edit: I don't know why Laravel accept it, validation rule digits_between use is_numeric function. You can try regex rule:

['thread_item_price' => 'regex:/^\d{0,4}\.\d{2}$/'];
like image 23
Ján Kyselica Avatar answered Oct 10 '22 20:10

Ján Kyselica