Forms, Flows and Production · Lesson 21 of 25
Form Validation in LWC
Base input components already know how to validate: required, pattern, type="email", min, max and length limits all produce Salesforce-styled error messages. Your job is to trigger validation at the right time, add custom rules, and never send invalid data to the server – while remembering that the server validates again.
In this lesson
- Built-in rules on lightning-input
- Validating every field before saving
- Custom messages and cross-field rules with setCustomValidity
- Client vs server validation
Built-in rules and validating the whole form
<!-- partnerSignup.html -->
<template>
<lightning-card title="Partner sign-up">
<div class="slds-p-horizontal_small">
<lightning-input label="Company" name="company" required onchange={handleChange}></lightning-input>
<lightning-input label="Work email" name="email" type="email" required onchange={handleChange}></lightning-input>
<lightning-input label="GSTIN" name="gstin" pattern="[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z][0-9A-Z]{3}"
message-when-pattern-mismatch="Enter a 15-character GSTIN, e.g. 27ABCDE1234F1Z5" onchange={handleChange}></lightning-input>
<lightning-input label="Team size" name="teamSize" type="number" min="1" max="500" onchange={handleChange}></lightning-input>
<lightning-button label="Submit" variant="brand" onclick={handleSubmit}></lightning-button>
<p>{result}</p>
</div>
</lightning-card>
</template>
// partnerSignup.js
import { LightningElement } from 'lwc';
export default class PartnerSignup extends LightningElement {
form = {};
result = '';
handleChange(event) {
this.form = { ...this.form, [event.target.name]: event.detail.value };
}
handleSubmit() {
// reportValidity() shows each field's error; checkValidity() would only return true/false
const allValid = [...this.template.querySelectorAll('lightning-input')]
.reduce((valid, input) => input.reportValidity() && valid, true);
this.result = allValid ? `Submitted: ${JSON.stringify(this.form)}` : 'Please fix the highlighted fields';
}
}
▌Partner sign-up
Company [] Work email [] GSTIN [] Team size [] [Submit]
› type “Acme Partners” into Company
▌Partner sign-up
Company [Acme Partners] Work email [] GSTIN [] Team size [] [Submit]
› type “asha@acme” into Work email
▌Partner sign-up
Company [Acme Partners] Work email [asha@acme] GSTIN [] Team size [] [Submit]
› type “27ABCDE1234” into GSTIN
▌Partner sign-up
Company [Acme Partners] Work email [asha@acme] GSTIN [27ABCDE1234] Team size [] [Submit]
› click “Submit”
▌Partner sign-up
Company [Acme Partners] Work email [asha@acme] ⚠ You have entered an invalid format. GSTIN [27ABCDE1234] ⚠ Enter a 15-character GSTIN, e.g. 27ABCDE1234F1Z5 Team size [] [Submit]
Please fix the highlighted fields
› clear Work email and type “asha@acme.com”
▌Partner sign-up
Company [Acme Partners] Work email [asha@acme.com] GSTIN [27ABCDE1234] ⚠ Enter a 15-character GSTIN, e.g. 27ABCDE1234F1Z5 Team size [] [Submit]
Please fix the highlighted fields
› clear GSTIN and type “27ABCDE1234F1Z5”
▌Partner sign-up
Company [Acme Partners] Work email [asha@acme.com] GSTIN [27ABCDE1234F1Z5] Team size [] [Submit]
Please fix the highlighted fields
› clear Team size and type “40”
▌Partner sign-up
Company [Acme Partners] Work email [asha@acme.com] GSTIN [27ABCDE1234F1Z5] Team size [40] [Submit]
Please fix the highlighted fields
› click “Submit”
▌Partner sign-up
Company [Acme Partners] Work email [asha@acme.com] GSTIN [27ABCDE1234F1Z5] Team size [40] [Submit]
Submitted: {"company":"Acme Partners","email":"asha@acme.com","gstin":"27ABCDE1234F1Z5","teamSize":"40"}reportValidity()runs the field's rules and shows the message;checkValidity()only returns a boolean.- The
reducewithinput.reportValidity() && validcallsreportValidity()on every input – so all errors appear at once – instead of stopping at the first invalid one, whichevery()would do. message-when-*attributes replace generic messages with helpful ones.
Custom and cross-field rules
For rules the built-ins can't express – "end date after start date", "this email is already registered" – set a message with setCustomValidity(), then call reportValidity(). An empty string clears it. To reach one specific input, give it an lwc:ref:
<!-- leaveRequest.html -->
<template>
<lightning-input type="date" label="From" name="from" value={from} onchange={handleChange}></lightning-input>
<lightning-input type="date" label="To" name="to" value={to} onchange={handleChange} lwc:ref="toDate"></lightning-input>
<lightning-button label="Request leave" onclick={submit}></lightning-button>
<p>{status}</p>
</template>
// leaveRequest.js
import { LightningElement } from 'lwc';
export default class LeaveRequest extends LightningElement {
from = '2026-12-20';
to = '';
status = '';
handleChange(event) {
this[event.target.name] = event.detail.value;
}
submit() {
const toInput = this.refs.toDate;
if (this.to && this.to < this.from) {
toInput.setCustomValidity('The end date must be on or after the start date');
} else {
toInput.setCustomValidity(''); // clear the custom error
}
if (toInput.reportValidity() && this.to) {
this.status = `Leave requested: ${this.from} → ${this.to}`;
} else if (!this.to) {
this.status = 'Choose an end date';
}
}
}
From [2026-12-20] To [] [Request leave] › clear To and type “2026-12-18” From [2026-12-20] To [2026-12-18] [Request leave] › click “Request leave” From [2026-12-20] To [2026-12-18] ⚠ The end date must be on or after the start date [Request leave] › clear To and type “2026-12-24” From [2026-12-20] To [2026-12-24] ⚠ The end date must be on or after the start date [Request leave] › click “Request leave” From [2026-12-20] To [2026-12-24] [Request leave] Leave requested: 2026-12-20 → 2026-12-24
Why not querySelector('lightning-input[name="to"]')?
On base components, LWC sets name, label and value as JavaScript properties, not HTML attributes – so attribute selectors like [name="to"] find nothing and your code fails with "Cannot read properties of null". Use lwc:ref, or a data- attribute (data-field="to"), which really is an attribute.
Always validate on the server too
Client validation is for a good experience, not for security: anyone can call your Apex method directly. Repeat the important rules in Apex (or with validation rules on the object), and show the server's message when it rejects a save.
Practice
Try it yourself
Validate a 6-digit Indian PIN code with a pattern and a friendly message, and show "Valid PIN" when it passes.
Show solution
<!-- pinCode.html --> <template> <lightning-input label="PIN code" pattern="[1-9][0-9]{5}" message-when-pattern-mismatch="Enter a 6-digit PIN code" onchange={handleChange}></lightning-input> <lightning-button label="Check" onclick={check}></lightning-button> <p>{message}</p> </template>// pinCode.js import { LightningElement } from 'lwc'; export default class PinCode extends LightningElement { message = ''; handleChange() { this.message = ''; } check() { const input = this.template.querySelector('lightning-input'); this.message = input.reportValidity() ? 'Valid PIN' : ''; } }PIN code [] [Check] › type “41100” into PIN code PIN code [41100] [Check] › click “Check” PIN code [41100] ⚠ Enter a 6-digit PIN code [Check] › clear PIN code and type “411001” PIN code [411001] [Check] › click “Check” PIN code [411001] [Check] Valid PIN
Quick check
Difference between reportValidity and checkValidity?
reportValidity shows the error message; checkValidity only returns true or false.
How do you add a custom error to a lightning-input?
input.setCustomValidity('message'), then input.reportValidity().
How do you clear a custom error?
Call setCustomValidity with an empty string.
Summary
- Use built-in rules (required, pattern, type, min/max) with clear message-when-* texts.
- Before saving, call reportValidity on every input so all errors show.
- Express custom and cross-field rules with setCustomValidity – and validate on the server too.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.