2

How can I display required field error if no option is selected? Making 'required="true"' is not working on button click.

<lightning:radioGroup 
        aura:id="mygroup"
        name="radioButtonGroup"
        label=" My Label "
        options="{! v.options }"
        required="true"
        value="{! v.radioGrpValue }"
        onchange="{! c.handleChange }"
        />
  • When do you want to display the error to the user? – itzmukeshy7 Sep 24 '18 at 4:54
  • Actually, I want to call this component in the Screen Flow, so when 'NEXT' button is clicked without selecting any option from the radioGroup. – Mahwish Sep 24 '18 at 4:55
  • 1
    So to trigger the field validation you have to execute a method on this field input.showHelpMessageIfInvalid(); this will highlight any error for the field. – itzmukeshy7 Sep 24 '18 at 4:58
  • This is my controller code so far btnPressed: function(cmp, event, helper) { var selectedRadioOption = cmp.find("mygroup"); if ($A.util.isEmpty(selectedRadioOption.get("v.value"))){ // show error somehow } else{ var actionClicked = event.getSource().getLocalId(); var navigate = cmp.get('v.navigateFlow'); navigate(actionClicked); } } – Mahwish Sep 24 '18 at 4:58
  • @itzmukeshy7 Thank you so much, it worked! – Mahwish Sep 24 '18 at 5:01
4

To trigger the lightning validation on the fields you can follow this approach:

Component

<lightning:radioGroup 
    aura:id="validate"
    name="radioButtonGroup"
    label=" My Label "
    options="{! v.options }"
    required="true"
    value="{! v.radioGrpValue }"
    onchange="{! c.handleChange }"
    />

Controller

btnPressed: function(cmp, event, helper) {
    if (helper.isValid(cmp)){
        var actionClicked = event.getSource().getLocalId();
        var navigate = cmp.get('v.navigateFlow');
        navigate(actionClicked);
    }
}

Helper

isValid: function (c, id) {
    var validateFields = c.find(id || 'validate');
    var isValid;
    if (validateFields) {
        isValid = [].concat(validateFields).reduce(function (validSoFar, input) {
            input.showHelpMessageIfInvalid();
            return validSoFar && input.get('v.validity').valid;
        }, true);
    }
    return isValid;
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.