Form validation issue

I have a form that takes general information. One of those inputs is for an email address. So I used the email validator, it works but not like it should imo. I don’t think a blank or null value should be validated. I don’t want to require the email address because some people might not have one or care to even use one.

What I want and expect is for the email input to validate ONLY valid addresses and when blank forget client and server side validation.

What I have tried and doesn’t work. Am I correct in my approach ?? Other ideas

$form->field($model, 'email')->input('email');

public function rules() {
    return [
        ['email', 'email', 'when' => function($model) { return false;}, 'whenClient' => "function(attribute, value) {return false;}"]
    ];
}

Remove ‘email’ from the ‘required’ rule?

Then it won’t validate a proper email address

Hi @jasin,

I believe that a simple email validator is enough for your use case.

public function rules() {
    return [
        ['email', 'email', ]
    ];
}

This setting will skip validation when the input is null or an empty string.

Please check skipOnEmpty property in the API reference (
https://www.yiiframework.com/doc/api/2.0/yii-validators-validator#$skipOnEmpty-detail). It is true by default.

No this doesn’t work like I want it to work.

'skipOnEmpty' => true

will highlight the box and add a green check mark and

'skipOnEmpty' => false

will highlight the box and leave a message that says the email address is not valid.

the result I want is a box that isn’t validated at ALL when the value is null or empty.

I see.

Then you can try to use when and whenClient.
Something like this:

return [
    ['email', 'email', 'when' => function($model) { return $model->email == '''; },
        'whenClient' => "function (attribute, value) { return $('#email').val() == ''}",
    ],
    ...
];