3

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!

2 Answers 2

4

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.

0

You can make use of focus() method available in lightning:input/select

You can use:

var allValid = cmp.find('field').reduce(function (validSoFar, inputCmp) { //inputCmp.reportValidity(); 
**inputCmp.focus();**
return validSoFar && inputCmp.checkValidity(); 
}, true);

Then reset the focus to appropriate field and you'll see the all errors listed under the field.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .