Lightning Component – Custom Error Message Not Displayed in Table Cell

I have the following piece of code

<aura:iteration items="{!v.wrapAccountList}" var="arItem" indexVar="index">  
                <tr>
                    <td>
                        <lightning:select name="rejectReasonPick" label="" aura:id="rejectrn" value="{!arItem.acc.rejectReason}">
                    </td>
<td>
<button aura:id="addButton" iconName="action:close" alternativeText="Reject" data-index="{!index}" onclick="{!c.actionOnReject}">Reject</button>
</td>
</tr>

…….

I have the following code in my jscontroller/helper

actionOnRejectHelper : function(component, event, helper) {
    event.preventDefault();
    var whichOne = event.currentTarget.dataset.index;
    console.log(whichOne);

    var wrapperList = component.get("v.wrapAccountList");//Here wrapAccountList is the wrapper list that was being iterated in the component
    var rejectReason = wrapperList[whichOne].acc.rejectReason;
    var accountRequestId = wrapperList[whichOne].acc.Id;

    var rejectren = component.find("rejectrn");
    console.log('rejectren'+rejectren[whichOne].value);
    if(rejectReason == ""){
        rejectren[whichOne].set("v.errors", [{message:"Please enter value"}]);
        console.log('rejectren[whichOne]'+rejectren[whichOne]);
        $A.util.addClass(rejectren[whichOne], 'slds-has-error');//add red border
    }
    else{
       $A.util.removeClass(rejectren[whichOne], "slds-has-error"); // remove red border
       $A.util.addClass(rejectren[whichOne], "hide-error-message"); 

//Rest of the code
       },

Here my issue is that

$A.util.addClass(rejectren[whichOne], 'slds-has-error'); 

is working and the field is being marked with red highlight.

However, the line above is not working

rejectren[whichOne].set("v.errors", [{message:"Please enter value"}]);

Error message is not being displayed

Where am I going wrong in this?

Best Answer

For adding custom error messages you might need to add either span or div html tags with proper formatting just above your component.

<div aura:id="error" class="slds-hide format-error-text">Show This error</div>
<lightning:select name="rejectReasonPick" label="" aura:id="rejectrn" value="{!arItem.acc.rejectReason}" />

Then in your controller you can access the error component and either show or hide it.

if(rejectReason == ""){
        //rejectren[whichOne].set("v.errors", [{message:"Please enter value"}]);
        $A.util.addClass(errorDiv[whichOne],"slds-show");
        console.log('rejectren[whichOne]'+rejectren[whichOne]);
        $A.util.addClass(rejectren[whichOne], 'slds-has-error');//add red border
    }

Hope this helps!