2

How could I enforce that one of two attributes is required in a lightning component?

For example:

<aura:event type="COMPONENT" description="UpdateRPGFlowGraphEvent">
    <aura:attribute name="flow" type="zced__.RPG_Flow__c"/>
    <aura:attribute name="flowId" type="String"/>
</aura:event>

I would like to always be sure that the flow or flowId is present in the component provided above.

I could put both flow and flowId to be required, but then any time I use the component (the event component in this case) I would have to provide a stub data for one of the components.

  • You're asking about a lightning component, but your code is for a lightning event. Are you asking about validating an event's attributes or a components? – pchittum Jun 20 '18 at 18:30
3

There's no way to specify that one of two elements are required in markup. Even in the documentation, when there's two or more fields where one is required, both attributes show as "not required" but the documentation states you must use one or the other. In other words, you can't enforce it programmatically, but you can provide information in the attribute's documentation.

3

I guess for me the question is this: required in what case?

In other words at what point do you need to validate that one or the other attribute is populated?

And then how do you want the component to respond to that state? Probably abort/block the server call, and then notify the user that the component cannot proceed, I would think.

Let's say, for instance when the user clicks a button, you want to then look to see that you have at least one or the other value.

handleButtonClick : function(component, event, helper) { 
    let flowVar = component.get("v.flow");
    let flowIdVar = component.get("v.flowId");

    if (flowVar || flowIdVar) {
       //if neither attribute is set, will be skipped
       //but if at least one is set, you're good to go
    } else {
        let toast = $A.get("e.force:showToast");
        // do something that tells the user to try again. 
        toast.setParams({
            title: "Oops!",
            message: "You must enter either a flow or flow id value"
       });
       toast.fire();
    }
}

As your question talks about components, I wrote this answer solving for this in a component context. If you are, in fact, looking to validate an aura:event, events do not have validation code. However, you could simply validate before firing, wherever you do that. You could also test for at least one value on the listening side.

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.