Hello friends, In this post you will see an example that helps you to put validation on email field in lightning web components. This so simple to implement, you can use it on both inputtype="email" or inputtype="text". So let's get started,

Email field validation in lightning web component

In this example, I am using a regex expression to check the email validity.

EmailValidation.html

 <template>
<lightning-card title="Validate Email">
<lightning-layout>
<lightning-layout-Item padding="around-small" size="6">
<lightning-input type="text" data-id="txtEmailAddress" label="Email Address" required="true">
</lightning-input><br/>
<lightning-button label="Submit" onclick={handleEmailValidation} variant="brand"></lightning-button>
</lightning-layout-Item>
</lightning-layout>
</lightning-card>
</template>
EmailValidation.js
 import { LightningElement } from 'lwc';
export default class EmailValidation extends LightningElement {
handleEmailValidation() {
var flag = true;
const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
let email = this.template.querySelector('[data-id="txtEmailAddress"]');
let emailVal = email.value;
if (emailVal.match(emailRegex)) {
email.setCustomValidity("");

} else {
flag = false;
email.setCustomValidity("Please enter valid email");
}
email.reportValidity();
return flag;
}
}
EmailValidation.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__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</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.