Validate Fields on UI in LWC

Sometimes we need to set field validation on UI level for the integrity of the data. So, Today we are going to learn in this article. How we can achieve this.

validateFields.html

<template>
    <lightning-record-edit-form object-api-name="Account" >
        <lightning-card >
            <lightning-messages></lightning-messages>
            <div class="slds-grid slds-wrap">
                <div class="slds-size_1-of-2">
                    <lightning-input-field field-name="Name" required>
                    </lightning-input-field>
                </div>
                <div class="slds-size_1-of-2">
                    <lightning-input-field field-name="AccountNumber" required>
                    </lightning-input-field>
                </div>
            </div>
            <div class="slds-grid slds-wrap">
                <div class="slds-size_1-of-2">
                    <lightning-input-field field-name="AccountSource" required>
                    </lightning-input-field>
                </div>
                <div class="slds-size_1-of-2">
                    <lightning-input-field field-name="Site" required>
                    </lightning-input-field>
                </div>
            </div>
            <div class="slds-align_absolute-center">
                <lightning-button class="slds-m-top_small" onclick={validateFields} variant="brand" type="submit" label="Save">
                </lightning-button>
            </div>
        </lightning-card>
    </lightning-record-edit-form>
</template>

validateFields.js

import { LightningElement } from 'lwc';

export default class ValidateFields extends LightningElement {
    validateFields() {
        this.template.querySelectorAll('lightning-input-field').forEach(element => {
            element.reportValidity();
        });
    }
}

validateFields.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
        <target>lightning__AppPage</target>
    </targets>
</LightningComponentBundle>

I hope you have enjoyed the article. You can comment below, If you have any queries related above topic. Subscribe our blog for the latest updates.

Follow us on twitter and join our WhatsApp group.