[SalesForce] Reset validity on input

I have a registration form with Lightning inputs and validations, ex.:

<lightning:input aura:id="email"
                 type="email"
                 label="Email"
                 name="email"
                 required="true"
                 messageWhenValueMissing="Please enter an email address."
                 value="{!v.email}" />

The form is displayed based on state. If the user cancels the registration, the form fields are hidden.

If validity has been triggered on any field and the user cancels the registration, if they start the registration again then validity is still showing on that field. I'd like to be able to remove validity from a field if the user cancels.

I tried something like this:

var email = component.find("email");
email.set("v.validity", false);

I'm not sure how to do this. Any thoughts?

Best Answer

Because validity attribute is read-only, so you cannot set any values on that attribute. Excerpt from the documentation:

This validity attribute is a read-only object with the following boolean properties.


However, with a quick test, seems you can use an aura:if here by utilizing it as below.

<!-- declare an attribute with default as true, so that the input is rendered first time -->
<aura:attribute name="reRender" type="Boolean" default="true" />

<aura:if isTrue="{!v.reRender}">
    <lightning:input aura:id="email"
                     type="email"
                     label="Email"
                     name="email"
                     required="true"
                     messageWhenValueMissing="Please enter an email address."
                     value="{!v.email}" />
</aura:if>

<!-- as an example here for User Cancel, substitute with your logic -->
<lightning:button label="Cancel Registration" onclick="{!c.cancel}" />

And within the JS Controller:

cancel : function(component){
    // your all other logic
    // ...
    component.set("v.reRender", false); // first set false to hide the block
    component.set("v.reRender", true); // then set back to true to re-render the block
}