0

Is there a way to validate form fields, that should remain "optional" (not required)?

Even if I set "required" to false in both cases (required or not), Magento nags at the optional field, when it is left empty (and there is a red "*", which marks a required field):

        <?= $block->isRequired() ?
            ' data-validate=\'{"required":false, "validate-custom-whatever":true}\'' :
            ' data-validate=\'{"required":false, "validate-custom-whatever":true}\''
        ?>

So, it seems to me, that there is no way to validate optional fields, without adding an extra case to the validator, like so (pseudocode):

if(value == '')
{
    return true
}
else
{
    // do validation and return true or false - depending on the validation result
}

Is this really the correct way, of doing it? Or is there a more beautiful "Magento way" of doing this?

1
  • Actually it's not about "removing the validation", as the updated title suggests.. The field should be optional (instead of required), but if the user fills the field (even though it is not required), it must be validated. I don't know, why this was changed, since it misleads those, who come accross my question.
    – fkowh
    Nov 18, 2021 at 9:16

1 Answer 1

1

Actually, Magento allows you to validate optional fields. You can do this as follows (for example):

<input type="text" data-validate='{"letters-only":true}' />

As you can see, you don't need to add "required":false param.

If this is not working for you and the field is still required, probably you have the validation rule added somewhere else. As you can see in Magento DevDocs, there are multiple ways to add validation rules for a field. I would also add that if your field is created using a uiComponent, then make sure that the validation rule is not defined in the component definition.

And regarding the red asterisk near the field name - please make sure that there are no parent elements having '_required' or 'required' class name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.