Sub topic 7
Blocking navigation with validate()
This chapter covers how a flow screen component stops the user from moving on when its input is invalid. It assumes you can already build a basic LWC with @api properties, that you know how to add a screen element in Flow Builder, and that you have read the earlier chapters on exposing a component and returning values with FlowAttributeChangeEvent.
Why a component needs its own validation
Flow Builder's built-in screen fields, such as Text and Number, have a Validation setting in which you enter a formula and an error message. A custom component has no such setting. The flow cannot see inside it, so the component has to answer one question for the flow: "Is it safe to move on?"
The component answers through a public method named validate(). The flow runtime calls it at the moments when the user tries to leave the screen. If the method says the input is invalid, the flow stays on the current screen and shows your error message.
When the flow calls validate()
The flow calls validate() on each component on the screen when the user clicks Next or Finish. It also calls validate() for Pause in some contexts, and you should not rely on that.
Back does not run validation. A user can always go back to fix an earlier answer, so a half-filled screen never traps them.
The flow only calls validate() if your component defines it. If you leave it out, the flow treats the component as valid every time.
The contract: what validate() returns
validate() is an @api method. It returns a plain object with these properties:
| Property | Type | Meaning |
|---|---|---|
| `isValid` | Boolean | `true` lets the flow continue. `false` blocks navigation. |
| `errorMessage` | String | The text shown to the user when `isValid` is `false`. |
The method must be decorated with @api. A method without @api is private, and the flow cannot see it. The flow then behaves as if no validation exists, and nothing warns you about it.
A complete example
The Quantity Picker from the earlier chapters accepts a number. This version rejects anything that is not a whole number greater than zero. First, the meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>Quantity Picker</masterLabel>
<targets>
<target>lightning__FlowScreen</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__FlowScreen">
<property name="label" type="String" role="inputOnly" label="Field label" default="Quantity"/>
<property name="quantity" type="Integer" label="Quantity"/>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>The template shows a number input and reports edits to the handler:
<template>
<lightning-input
type="number"
label={label}
value={quantity}
min="1"
step="1"
onchange={handleChange}>
</lightning-input>
</template>The JavaScript class stores the value, tells the flow about it, and implements validate():
import { LightningElement, api } from 'lwc';
import { FlowAttributeChangeEvent } from 'lightning/flowSupport';
export default class QuantityPicker extends LightningElement {
@api label = 'Quantity';
@api quantity;
handleChange(event) {
const parsed = parseInt(event.detail.value, 10);
this.quantity = Number.isNaN(parsed) ? undefined : parsed;
this.dispatchEvent(new FlowAttributeChangeEvent('quantity', this.quantity));
}
@api validate() {
if (Number.isInteger(this.quantity) && this.quantity > 0) {
return { isValid: true };
}
return {
isValid: false,
errorMessage: 'Enter a whole number greater than zero.'
};
}
}Three details are worth noticing.
handleChangeconverts the text into an integer. An empty field becomesundefined, whichvalidate()then rejects.validate()reads the component's own state (this.quantity), not the DOM. That keeps it simple and testable.- The
min="1"attribute onlightning-inputis a browser-level hint. Users can still type0or-5, or leave the field empty. The flow-level check invalidate()is the one that actually blocks navigation.
Validation is separate from the output value
Reporting a value and validating it are independent. FlowAttributeChangeEvent sends quantity to the flow on every edit, even when the value is invalid. The flow variable therefore holds the latest value at all times. validate() only decides whether the user may leave the screen.
This matters for two reasons:
- A flow variable can hold an invalid value while the user is still on the screen. It never reaches later elements, because navigation is blocked.
- If the user clicks Back from the screen, the invalid value is still stored in the flow variable. Plan for that if later elements read the same variable.
Showing errors before the user clicks Next
The error from validate() appears only after a navigation attempt. If you want feedback while the user types, or you want the error displayed beside the field, use the field's own validity API. lightning-input supports setCustomValidity() and reportValidity().
import { LightningElement, api } from 'lwc';
import { FlowAttributeChangeEvent } from 'lightning/flowSupport';
export default class QuantityPickerInline extends LightningElement {
@api label = 'Quantity';
@api quantity;
handleChange(event) {
const parsed = parseInt(event.detail.value, 10);
this.quantity = Number.isNaN(parsed) ? undefined : parsed;
this.dispatchEvent(new FlowAttributeChangeEvent('quantity', this.quantity));
}
get errorText() {
if (Number.isInteger(this.quantity) && this.quantity > 0) {
return '';
}
return 'Enter a whole number greater than zero.';
}
@api validate() {
const input = this.template.querySelector('lightning-input');
input.setCustomValidity(this.errorText);
const isValid = input.reportValidity();
return isValid
? { isValid: true }
: { isValid: false, errorMessage: this.errorText };
}
}In this version setCustomValidity('') clears any earlier error, and a non-empty string marks the input invalid. reportValidity() draws the red border and message under the field, and also returns whether the input is valid. The method returns the same message to the flow, so the user sees the message in both places.
If you show the message in both places, check that the wording works in both. The flow's banner shows it away from the field, so it should make sense without the field next to it.
Validating several fields
A component with more than one input should check all of them and report one message. Do not return at the first failure, because the user then fixes errors one click at a time.
@api validate() {
const problems = [];
if (!this.firstName) {
problems.push('First name is required.');
}
if (!this.email || !this.email.includes('@')) {
problems.push('Enter a valid email address.');
}
if (problems.length === 0) {
return { isValid: true };
}
return { isValid: false, errorMessage: problems.join(' ') };
}The flow shows errorMessage as one string. It does not render a list, so join the messages into a sentence or short paragraph.
Edge cases and gotchas
- Return an object every time. Returning
undefinedornullfrom a code path can cause a runtime error or be treated as valid, depending on the host. Make sure every branch returns an object withisValid. - Keep it synchronous. The flow expects the result immediately. An
asyncmethod returns a Promise, and the flow does not wait for it. Do server checks, such as uniqueness lookups, in an Apex action element on a later screen, or validate in the component and store the outcome before the user clicks Next. - Do not mutate input properties to "fix" values. Flow passes values to
@apiproperties as read-only. If you need a cleaned-up value, copy it into a local field and send it back withFlowAttributeChangeEvent. - Validate when the component is hidden. If a component sits in a section that is conditionally visible, the flow may not call
validate()on it. Do not use a hidden required component as the only guard for data you need. - Empty is not the same as missing. A required property that the flow never set arrives as
undefined. A field the user cleared might be an empty string. Handle both. - Do not call validate() yourself to move on. You can call it from your own code, for example inside a custom Next button, before you dispatch a navigation event. The next chapter covers navigation events, and the same rule applies there: check validity first.
- Messages are not translated for you. If your org is multilingual, use a custom label import for
errorMessageinstead of a literal string.
Testing validate()
Because validate() is a normal method, you can test it in Jest without a flow. Create the component, set its properties, and call the method.
import { createElement } from 'lwc';
import QuantityPicker from 'c/quantityPicker';
describe('c-quantity-picker validate()', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('rejects an empty value', () => {
const element = createElement('c-quantity-picker', { is: QuantityPicker });
document.body.appendChild(element);
const result = element.validate();
expect(result.isValid).toBe(false);
expect(result.errorMessage).toBe('Enter a whole number greater than zero.');
});
it('accepts a positive integer', () => {
const element = createElement('c-quantity-picker', { is: QuantityPicker });
element.quantity = 3;
document.body.appendChild(element);
expect(element.validate().isValid).toBe(true);
});
});To check it in Flow Builder, add the component to a screen, run the flow with Debug, leave the field empty, and click Next. The screen should stay put and show your message. Then enter a valid number and confirm the flow moves on.
Choosing between validation approaches
| Approach | Blocks navigation | Shows error beside field | Best for |
|---|---|---|---|
| `validate()` only | Yes | No, flow banner only | Simple rules, single messages |
| `validate()` plus `setCustomValidity()` | Yes | Yes | Forms with several fields |
| `setCustomValidity()` only | No | Yes | Never use this alone in a flow |
| Flow screen field validation formula | Yes | Yes | Rules on standard fields, not custom components |
Exercise
A flow screen contains your component. The user clicks Back, and the flow moves to the previous screen even though the component's field is empty. A teammate says validate() is broken. Is it?
Show answer
No. The flow does not run validate() for Back, so the user can always return to an earlier screen. Validation applies to Next and Finish.
Exercise
You add a method named validate() to your component but forget the @api decorator. The user leaves a required field empty and clicks Next. What happens, and why?
Show answer
The flow moves to the next screen. Without @api the method is private, so the flow cannot find it and treats the component as valid. No error is raised.
Exercise
Write a validate() method for a component with an @api property named email that must contain "@". It should return the message "Enter a valid email address." when the check fails.
Show answer
@api validate() { if (typeof this.email === 'string' && this.email.includes('@')) { return { isValid: true }; } return { isValid: false, errorMessage: 'Enter a valid email address.' }; }