[SalesForce] How to show custom validation message for lightning Select

I am trying to display custom validation message for lightning Select tag based aura id but validation is not coming on lightning Select tag.

Component Code:

<aura:component >
    <lightning:select name="select1" label="How many tickets?" aura:Id="leadtimesel" messageWhenValueMissing="Please choose one">
        <option value="">choose one...</option>
        <option value="1">one</option>
        <option value="2">two</option>
        <option value="3">three</option>
    </lightning:select>
    <lightning:button variant="brand" label="Brand" title="Brand action" onclick="{! c.handleClick }" />

</aura:component>

JS Code:

({
    handleClick : function(component, event, helper){
      var firstNameField = component.find("leadtimesel");
        var value = firstNameField.get("v.value");
        alert(value);
          if(value===''||value===null) {
             alert(123);
            firstNameField.showHelpMessageIfInvalid();
        
 
        }
    }
})

Thanks,
Anil Kumar

Best Answer

You are missing required attribute from the component.

<lightning:select name="select1" label="How many tickets?" required="true" aura:id="leadtimesel" messageWhenValueMissing="Please choose one">
    <option value="">choose one...</option>
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3">three</option>
</lightning:select>
<lightning:button variant="brand" label="Brand" title="Brand action" onclick="{! c.handleClick }" />

As per question * needed to be hidden, This can be easily achieved by. Writing a css and importing that in cmp.

Import this CSS and change your lightning:select to add a class so that you know which slds-required class to remove.

<ltng:require styles="{!$Resource.hideAsterisk + '/css/style.css'}" />
<lightning:select name="select1" label="How many tickets?" class="noAsterisk" required="true" aura:id="leadtimesel" messageWhenValueMissing="Please choose one">

Then add this to style.css static resource.

.noAsterisk .slds-required {
    display: none;
}

This will hide your * sign.

Related Topic