How to add custom validation on fields in LWC Salesforce

by Rijwan Mohmmed
how-to-add-validation-on-fields-in-lwc-salesforce

Hello friends , today we will learn add custom validation on fields in LWC (lightning web component. We use validation on fields for filter the correct data so our data should be good in database and these things show on the spot to the user end. By this way user also get notified.

We create a simple form in which we will show fields validation like phone no , email format and field required.

Checkout validation in lightning component : validation in Lightning component

TechdicerLWCValidation.html :

<template>
    <div class="slds-tabs_card">
		<div class="slds-page-header">
			<div class="slds-page-header__row">
				<div class="slds-page-header__col-title">
					<div class="slds-media">
						<div class="slds-media__figure">
							<span class="slds-icon_container slds-icon-standard-opportunity">
								 <lightning-icon icon-name="standard:recipe" alternative-text="recipe" title="recipe"></lightning-icon>
                            </span>
						</div>
						<div class="slds-media__body">
							<div class="slds-page-header__name">
								<div class="slds-page-header__name-title">
									<h1>
										<span>LWC Custom Validation on fields</span>
										<span class="slds-page-header__title slds-truncate" title="TechDicer">TechDicer</span>
									</h1>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div> <br/>
    <lightning-card title="Personal Info">
        <p class="slds-var-p-around_small">
            <lightning-layout multiple-rows>
                <lightning-layout-item padding="around-small" size="12" medium-device-size="6" large-device-size="6">
                    <lightning-input name="name" class="fieldvalidate" type="text" label="Name" required></lightning-input>
                    <lightning-input name="phone" class="fieldvalidate" type="tel" label="Phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}$" message-when-pattern-mismatch="Please enter a valid phone number" required onchange={handlePhoneformat}></lightning-input>
                    <lightning-input name="company" class="fieldvalidate" type="text" label="Company" required></lightning-input>
                </lightning-layout-item>
                <lightning-layout-item padding="around-small" size="12" medium-device-size="6" large-device-size="6">
                    <lightning-input name="email" class="fieldvalidate" type="email" label="Email" pattern="[A-Za-z0-9._-]+@[a-z0-9-]+.[a-z]{2,}$" message-when-pattern-mismatch="Please enter a valid email" required></lightning-input>
                    <lightning-combobox name="country" class="fieldvalidate" label="Country" options={countryOptions} required></lightning-combobox>
                    <lightning-input name="pincode" class="fieldvalidate" type="number" label="Pin Code" min="1000" max="999999" message-when-range-overflow="Please enter a correct pincode" message-when-range-underflow="Please enter a correct pincode"></lightning-input>
                </lightning-layout-item>
                <lightning-layout-item size="12" class="slds-var-p-top_small">
                    <lightning-button class="slds-align_absolute-center" variant="brand" label="Submit" onclick={handleValidation}></lightning-button>    
                </lightning-layout-item>
            </lightning-layout>
        </p>
    </lightning-card>
</template>

TechdicerLWCValidation.js :

import { LightningElement } from 'lwc';
export default class TechdicerLWCValidation extends LightningElement {
countryOptions = [
        { "label": "India", "value": "India" },
        { "label": "Sri lanka", "value": "Sri lanka" },
        { "label": "Pakistan", "value": "Pakistan" },
        { "label": "Australia", "value": "Australia" },
        { "label": "Indonesia", "value": "Indonesia" }
    ];

    //check field validation
    handleCheckValidation() {
        let isValid = true;
        let inputFields = this.template.querySelectorAll('.fieldvalidate');
        inputFields.forEach(inputField => {
            if(!inputField.checkValidity()) {
                inputField.reportValidity();
                isValid = false;
            }
        });
        return isValid;
    }

    handleValidation() {
        if(this.handleCheckValidation()) {
            //send data to server side
        }
    }
}

TechdicerLWCValidation.js-meta.xml :

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>51.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__HomePage</target>
		<target>lightning__Tab</target>
	</targets>
</LightningComponentBundle>
What’s your Reaction?
+1
1
+1
0
+1
0
+1
0
+1
1
+1
0

You may also like

Leave a Comment