Morteza Negahi
Morteza Negahi

Reputation: 3493

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',
]);

Upvotes: 5

Views: 8471

Answers (6)

majid behzadnasab
majid behzadnasab

Reputation: 123

according to laravel documentation 8 you must to set nullable rule for example:

 $validated = $request->validate([
            'firstName' => ['required','max:255'],
            'lastName' => ['required','max:255'],
            'branches' => ['required'],
            'services' => ['required' , 'json'],
            'contract' => ['required' , 'max:255'],
            'FixSalary' => ['nullable','numeric' , 'max:90000000'],
            'Percent' => ['nullable','numeric' , 'max:100'],
        ]);

in your case :

$this->validate($request, [
        'provinces_id' => 'required|numeric',
        'type' => 'required',
        'bed' => 'nullable|numeric',
]);

Upvotes: 1

Josh Chang
Josh Chang

Reputation: 55

In laravel 5.5 or versions after it, we begin to use nullable instead of sometimes.

Upvotes: 3

Harshan Madhuranga
Harshan Madhuranga

Reputation: 53

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

Upvotes: 4

William Turrell
William Turrell

Reputation: 3328

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

Upvotes: 3

Mahfuzul Alam
Mahfuzul Alam

Reputation: 3157

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

Upvotes: 3

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

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

Upvotes: 8

Related Questions