5

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',
]);
1
  • 1
    you should make it nullable Commented Oct 24, 2016 at 9:54

6 Answers 6

8

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

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

3

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

Comments

3

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

Comments

3

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.