Adding Validation Errors on Individual Inputs in custom Flow Screen Components – Part 3

Hola! So glad to see you here! 😀

So this is my third post of the series on handling validation in custom Flow Lightning components(no plans for the 4th one). Please make sure to give them a read before continuing further, otherwise this post may not make much sense.

Quick recap

In part 1, we discussed how to validate custom lightning components in Flow screens and the limitations associated with it. And in part 2, we addressed one of those limitations.

In this article, we will be discussing the second limitation which is how we can add multiple validations to individual field input, since the validation process only allows us to return a string for validation error. This enhancement relates more to the UI, to give users a more enriching experience.

Logic

So the idea is pretty simple, we use the sessionStorage of the browser to track which all inputs failed the validation, and accordingly add some alert text on those fields.

So let’s get into it!

FlowScreenCMPsValidation.cmp

<aura:component implements="lightning:availableForFlowScreens" access="global">
    
    <aura:handler name="init" value="{!this}" action="{!c.init}"/>
    
    <aura:attribute name="validate" type="Aura.Action" 
                    description="Custom validation function to run when the flow is navigated to the next screen. The function must evaluate the component and return values for isValid and errorMessage."
                    />
    <aura:attribute name="firstName" type="String"/>
    <aura:attribute name="lastName" type="String"/>
	
    <!-- Error Message Banner -->
    <div aura:id="errorHeader" class="pageLevelErrors slds-hide">
        <div class="desktop forcePageError">
            <div class="genericNotification">
                <span class="genericError" >
                    Review the errors on this page.
                </span>
            </div>
        </div>
    </div>
    
    <div id="firstName">
        <lightning:input aura:id="firstName" type="text" label="First Name" value="{!v.firstName}" required="true"/>
    </div>
    
    <div id="lastName">
		<lightning:input aura:id="lastName" type="text" label="Last Name" value="{!v.lastName}" required="true"/>    
    </div>

</aura:component>

FlowScreenCMPsValidationController.js

({
    init: function(component, event, helper) {
		
        // Set the validate attribute to a function that includes validation logic
        component.set('v.validate', function() {
            var isFirstNameValid=false;
            var firstName = component.get('v.firstName');
            if(firstName && firstName.length>0)
                isFirstNameValid = true;
            
            var isLastNameValid=false;
            var lastName = component.get('v.lastName');
            if(lastName && lastName.length>0) 
                isLastNameValid = true;
            
            if(isFirstNameValid && isLastNameValid){
                if(sessionStorage){
                    sessionStorage.removeItem('validationfailed'); sessionStorage.removeItem('firstName');
                    sessionStorage.removeItem('lastName'); sessionStorage.removeItem('isFirstNameValid');
                    sessionStorage.removeItem('isLastNameValid');
                }
                return { isValid: true };
            }
            else{
                if(sessionStorage){
                    sessionStorage.setItem('validationfailed',true); 
                    sessionStorage.setItem('isFirstNameValid',isFirstNameValid);
                    sessionStorage.setItem('isLastNameValid',isLastNameValid);
                    if(isFirstNameValid) 
                        sessionStorage.setItem('firstName',firstName);
                    else
                        sessionStorage.setItem('firstName','');
                    if(isLastNameValid)                    
                        sessionStorage.setItem('lastName',lastName);
                    else
                        sessionStorage.setItem('lastName','');
                }
                return { isValid: false, errorMessage: '' };
            }
        })
    }    
})

FlowScreenCMPsValidationHelper.js

({
	addValidation : function(component, event, elementId, validationMessage){
        
        var styleClass= 'slds-form-element__help validationCss';
        
        var input = component.find(elementId);
        $A.util.addClass(input,'slds-has-error');
        
        var inputElement = document.getElementById(elementId);
        
        var validationeElement = document.createElement("div");
        validationeElement.setAttribute("class",styleClass);
        validationeElement.textContent = validationMessage;
                
        inputElement.appendChild(validationeElement);
	
    }
})

FlowScreenCMPsValidation.css

.THIS .validationCss{
    font-size: .75rem;
    margin-top: .125rem;
    display: block;
    color: rgb(194, 57, 52);
}

FlowScreenCMPsValidationRenderer.js

({
	afterRender: function (component, helper){
    	this.superAfterRender();
        
        //Get inputs when validation failed
        if(sessionStorage){
            if(sessionStorage.getItem('validationfailed')){
                var errorHeader = component.find("errorHeader");
        		$A.util.removeClass(errorHeader,'slds-hide');
                
                if(sessionStorage.getItem('isFirstNameValid')==='true')
                    component.set('v.firstName',sessionStorage.getItem('firstName'));
                if(sessionStorage.getItem('isFirstNameValid')==='false')
                    helper.addValidation(component, event, 'firstName', 'Please enter First name');
                
                if(sessionStorage.getItem('isLastNameValid')==='true')
                    component.set('v.lastName',sessionStorage.getItem('lastName'));
                if(sessionStorage.getItem('isLastNameValid')==='false')
                    helper.addValidation(component, event, 'lastName', 'Please enter Last name');
            }
        }
	}
})

Demo!

Well, this concludes our series on Flow screen custom component validations.

Thank you for being an awesome reader! If you haven’t already, please subscribe to this blog for receiving all the latest updates straight into your inbox.  🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.