Pratik Shah
Pratik Shah

Reputation: 149

How to validate field only if it's value is entered in Laravel 4?

I am using Laravel 4 in which I have field email or pincode you can say.
So while using Laravel validator I want to check if it is email or not only if it's value is filled else it will ignore it..

Upvotes: 3

Views: 3164

Answers (3)

MaN1k
MaN1k

Reputation: 71

You can use "sometimes" rule to your rule list:

$v = Validator::make($data, array(
    'email' => 'sometimes|required|email',
));

http://laravel.com/docs/validation#conditionally-adding-rules

Upvotes: 7

warspite
warspite

Reputation: 632

You can simply have an email rule on the field. If you do not have a required on the field then it won't fail if empty, but when it is entered, it must be an email.

That will satisfy your use case above.

So...

$validator = Validator::make(
array('pincode' => 'email'),
... other field => rules
);

Upvotes: 1

JohnTaa
JohnTaa

Reputation: 2824

Laravel will not know about the value before posting your data, So you have to use javascript to check the email syntax validation

Upvotes: 0

Related Questions