Last updated on November 21, 2022
Typically we do the email validation with a regular expression which will validate the structure. The Regular expression can be useless even after it is validated in the format if the domain does not exist.
So validating with a regular expression is not enough, sometime you may be required to validate even more low-levelly. For any domain, MX records are responsible for delivering emails to the recipient addresses. So we gonna validate the MX record for the provided email address domain with Node Js’s build-in dns
module.
The Code
const dns = require('dns');
const email = '[email protected]';
const domain = email.split('@')[1];
dns.resolve(domain, 'MX', function(err, addresses) {
if (err) {
console.log('No MX record exists, so email is invalid.');
} else if (addresses && addresses.length > 0) {
console.log('This MX records exists So I will accept this email as valid.');
}