Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - prevent validation check on empty inputs

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?

like image 256
alex Avatar asked Mar 19 '17 14:03

alex


1 Answers

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'
];
like image 164
alex Avatar answered Nov 18 '22 08:11

alex