15

there is some input fields in a form and this is my rules defined in Model :

  public static $rules = [
    'name' => 'string',
    'email' => 'email',
    'phone' => 'sometimes|numeric',
    'mobile' => 'numeric',
    'site_type_id' => 'integer'
];

none of them are required. but when form is submitted, validation errors emerged that email should be an email address and so for other inputs.
in this situation having a field required is meaningless as laravel always validate field against rules.
I know when form is submitted empty fields have a null value.how should i prevent field validation for empty fields?

1
  • You can accept your own answer now I guess Commented Aug 26, 2019 at 12:32

1 Answer 1

34

Laravel 5.3 onwards nullable can be used for optional fields:

https://laravel.com/docs/validation#rule-nullable

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

so the rules array should be like this:

public static $rules = [
    'name' => 'nullable|string',
    'email' => 'nullable|email',
    'phone' => 'nullable|numeric',
    'mobile' => 'nullable|numeric',
    'site_type_id' => 'nullable|integer'
];
Sign up to request clarification or add additional context in comments.

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.