Hello friends, In this post you will see an example that helps you to put validation on fields in lightning web component. Validating fields in lightning web component is too easy so let's get started,
Field validation in lightning web component
This example works on every lightning input that present inside you component html page. so no need to validate each field individually through custom validation code.
FormValidation.html
<template>FormValidation.js
<lightning-card title="Form Validatation">
<lightning-layout>
<lightning-layout-Item padding="around-small" size="6">
<lightning-input type="text" data-id="txtFirstName" label="First Name" required="true">
</lightning-input>
</lightning-layout-Item>
<lightning-layout-Item padding="around-small" size="6">
<lightning-input type="text" data-id="txtLastName" label="Last Name" required="true">
</lightning-input>
</lightning-layout-Item>
</lightning-layout>
<lightning-layout>
<lightning-layout-Item padding="around-small" size="6">
<lightning-input type="number" data-id="txtAge" label="Age" required="true">
</lightning-input>
</lightning-layout-Item>
<lightning-layout-Item padding="around-small" size="6">
<lightning-input type="text" data-id="txtAddress" label="Address" required="true">
</lightning-input>
</lightning-layout-Item>
</lightning-layout>
<lightning-layout>
<lightning-layout-Item padding="around-small" size="12">.
<div class="slds-align_absolute-center">
<lightning-button data-id="btnSubmit" onclick={submitData} variant="brand" label="Submit">
</lightning-button>
</div>
</lightning-layout-Item>
</lightning-layout>
</lightning-card>
</template>
import { LightningElement } from 'lwc';FormValidation.js-meta.xml
export default class FormValidation extends LightningElement {
submitData(event) {
const isInputsCorrect = [...this.template.querySelectorAll('lightning-input')]
.reduce((validSoFar, inputField) => {
inputField.reportValidity();
return validSoFar && inputField.checkValidity();
}, true);
if (isInputsCorrect) {
//do something...
}
}
}
<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__RecordAction</target>
</targets>
</LightningComponentBundle>
Output:
Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.
0 Comments
Post a Comment