Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow empty value for Laravel numeric validation

How to set not require numeric validation for Laravel5.2? I just used this Code but when i don't send value or select box haven't selected item I have error the val field most be numeric... I need if request hasn't bed input leave bed alone. leave bed validate ...

$this->validate($request, [
        'provinces_id' => 'required|numeric',
        'type' => 'required',
        'bed' => 'numeric',
]);
like image 639
Morteza Negahi Avatar asked Oct 24 '16 09:10

Morteza Negahi


4 Answers

If I understood you correctly, you're looking for sometimes rule:

'bed' => 'sometimes|numeric',

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list

like image 82
Alexey Mezenin Avatar answered Nov 20 '22 18:11

Alexey Mezenin


In Laravel 6 or 5.8, you should use nullable. But sometimes keyword doesn't work on that versions.

like image 37
Harshan Madhuranga Avatar answered Nov 20 '22 19:11

Harshan Madhuranga


Use sometimes instead of required in validation rules. It checks if only there is a value. Otherwise it treats parameter as optional.

like image 2
Mahfuzul Alam Avatar answered Nov 20 '22 20:11

Mahfuzul Alam


You may need nullablesometimes and present didn't work for me when combined with integer|min:0 on a standard text input type - the integer error was always triggered.

A Note on Optional Fields

By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. Because of this, you will often need to mark your "optional" request fields as nullable if you do not want the validator to consider null values as invalid.

Tested with Laravel 6.0-dev

Full list of available rules

like image 2
William Turrell Avatar answered Nov 20 '22 19:11

William Turrell