[SalesForce] Setting Error Message on Lightning:select

I'm trying to understand how to add custom error messaging to the lightning:select base component.

I understand that I can use the validity object to check if there is bad data and set a respective custom message. What I am having trouble understanding is how to apply it to this scenario:

  1. I have a lightning:select component defined with the values "Red,Blue,Green".
  2. Because I want to force a selection, I've added "– None –" as the first value in the list.
  3. So I have "– None –,Red,Blue,Green"

How do I tell the base component that "– None –" is invalid and an error needs to be shown?

Thanks!

Best Answer

The magic happens when you combine the required, onchange, and messageWhenValueMissing attributes together.

<aura:attribute name="colors" type="String[]" default="Red,Green,Blue"/>
<lightning:select aura:id="select" name="select" 
                  label="Select a Color" 
                  required="true" onchange="{! c.onChange }" 
                  messageWhenValueMissing="Choose one!">
    <option value="">-- None --</option>
    <aura:iteration items="{!v.colors}" var="color">
            <option value="{!color}" text="{!color}"></option>
        </aura:iteration>
</lightning:select>

The error message specified by messageWhenValueMissing is shown when the first option is selected. You can also pair this solution with the showHelpMessageIfInvalid method to trigger the error from your JS controller.

Credits to @Eugene Kashida.