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?
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'
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With