Lightning:Input – Hide (Reset) Field Level Error message Enabled by using showHelpMessageIfInvalid()

All we need is an easy explanation of the problem, so here it is.

Have few Lightning:Input and Lightning:Select components in My Component A.
All the fields are having Required attribute as ‘true’.
Once fields are validated, Field level error (help) messages appear at the bottom of the field and will be there until input Field data is changed (is valid). I have used showHelpMessageIfInvalid() to enable this error message on field explicitly from controller.

I would like to Reset(Hide) the error messages on all these fields from Controller.
Is there any way to do this?
Looks like “errors” is not a valid attribute for Lightning:Input / Lightning:Select components. Below attempt failed.

component.find('FieldAuraID').set('v.errors', null);

Thanks

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

If you really wanted to hide error messages you could do something like this:

Component:

<div>
    <lightning:input label="First Name" aura:id="firstName" required="true"/>
    <lightning:button onclick="{!c.hideErrors}">Hide Errors</lightning:button>
</div>

Controller:

hideErrors : function(component, event, helper) {
    var el = component.find("firstName");
    $A.util.removeClass(el, "slds-has-error"); // remove red border
    $A.util.addClass(el, "hide-error-message"); // hide error message
}

Style:

.THIS .hide-error-message > .slds-form-element__help {

.THIS .hide-error-message > .slds-form-element > .slds-form-element__help {
    display: none;
}

But the internal DOM structure and class names of base components are subject to change so this isn’t a totally robust solution.

Method 2

In my case with hidden form the approach below was more appropriate:

<aura:component >
  <aura:attribute name="isVisible" type="Boolean" default="true" />
  <aura:attribute name="field1" type="String" />
  <aura:attribute name="fieldsValidity" type="Object[]" />

  <aura:if isTrue={!v.isVisible}">
    <lightning:input name="textInput" value="{!v.field1}" 
                     validity="{!v.fieldsValidity.field1}" />
  </aura:if>

  <lightning:button label="Clear" onclick={!c.clearErrors} />
</aura:component>

JS:

clearErrors: function(cmp){
   cmp.set('v.fieldsValidity.field1', null);

   cmp.set('v.isVisible', false);
   cmp.set('v.isVisible', true);
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply