Requirement : | ‹ | › |
Create a LWC which we will take information like First Name(Text) , Last Name(Text) and Phone(Tel) where these are mandatory fields. Give one button Named ‘Validate’ in the end of the form .On click of button it would show an error message if the mandatory fields are empty or the
phone is not in correct format.
Or in other words
Check validation
cmpValidateFields.html
<template>
<lightning-card title="Check Validation" icon-name="custom:custom63">
<lightning-input
label="First name"
class="validValue inputFirstName"
minlength="3"
field-level-help="This First Name is required"
message-when-bad-input="Your entry must be at least 3 characters."
placeholder="First name"
message-when-value-missing="Please enter your First Name"
required>
</lightning-input>
<br>
<lightning-input
label="Last name"
class="validValue inputLastName"
minlength="3"
field-level-help="This Last Name is required"
message-when-bad-input="Your entry must be at least 3 characters."
placeholder="Last name"
message-when-value-missing="Please enter your Last Name"
required>
</lightning-input>
<br>
<lightning-input
label="Phone"
class="validValue inputPhone"
placeholder="0412 345 678"
pattern="^(\s*\d\s*){10}$"
maxlength="12"
minlength="10"
field-level-help="This Phone is required"
message-when-bad-input="Phone number is not valid"
message-when-value-missing="Please enter your Phone Number"
required>
</lightning-input>
<br>
<center>
<lightning-button
variant="brand"
label="Validate"
onclick={handleValidation}>
</lightning-button>
</center>
</lightning-card>
</template>
cmpValidateFields.js
import { LightningElement, track } from 'lwc';
export default class cmpValidateFields extends LightningElement {
handleValidation() {
const allValid = [...this.template.querySelectorAll('.validValue')]
.reduce((validSoFar, inputCmp) => {
inputCmp.reportValidity();
return validSoFar && inputCmp.checkValidity();
}, true);
}
}
cmpValidateFields.js-meta.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__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
<target>lightning__Tab</target>
</targets>
</LightningComponentBundle>
Output :
Happy Learning !!
Comments
Post a Comment