Lightning Web Components – Making an LWC Screen Flow Component Required Before Submit

flow-screen-componentlightning-web-componentsscreen-flow

I have an LWC I wrote for a screen flow.
In this LWC the user needs to select a value from 1 to 10 by clicking on one of 10 icons.
The selection is passed back to the screen flow using an outputOnly property.
How can I make this selection mandatory before continuing to the next screen (same as I do when I mark a standard field mandatory)?

Best Answer

you can do this by using this function explained here

So for example, let's say I have a component like this,

Javascript

import { LightningElement, api, track } from 'lwc';

export default class LwcInFlow extends LightningElement {

@api number;

handleNumberChange(evt){
    this.number = evt.target.value;
}

@api
validate() {
    if(this.number != null) { 
        return { isValid: true }; 
    } 
    else { 
        // If the component is invalid, return the isValid parameter 
        // as false and return an error message. 
        return { 
            isValid: false, 
            errorMessage: '/*A message that explains what went wrong.*/' 
        }; 
    }
}

}

Html

<template>
    <lightning-input
    value={number} onchange={handleNumberChange}>
    </lightning-input>
</template>

XML

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>57.0</apiVersion>
<isExposed>true</isExposed>
<targets>
    <target>lightning__FlowScreen</target>
</targets>
<targetConfigs>
   <targetConfig targets="lightning__FlowScreen">
       <property name="number" label="Annual Revenue" type="Integer" role="outputOnly"/>
   </targetConfig>
</targetConfigs>
</LightningComponentBundle>

When I try to click next, without inputing the number, so number will be null, hence it won't let me go to the next screen and will show the error message from the validate function's else statement.

Hope it helps :)

Related Topic