There are several ways to validate an email address in JavaScript, but one common method is to use regular expressions. A regular expression is a pattern that can be used to match a string, and in this case, we can use it to match the format of an email address.
Here is an example of a regular expression that can be used to validate an email address in JavaScript:
Example 1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - checking email</title>
</head>
<body >
<div class="mail">
<h2>Input an email and Submit</h2>
<form name="form1" action="#">
<input type='text' name='text1'/>
<input type="button" name="submit" value="Submit" onclick="ValidateEmail(document.form1.text1)"/>
</form>
</div>
<script>
function ValidateEmail(inputText)
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.value.match(mailformat))
{
alert("Valid email id!");
document.form1.text1.focus();
return true;
}
else
{
alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
</script>
</body>
</html>
Example 2
var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (emailRegex.test(email)) {
console.log("Valid email address");
} else {
console.log("Invalid email address");
}
In this example, the emailRegex
variable contains the regular expression pattern, which is used to test the email address using the test()
method. If the email address matches the pattern, the test()
method will return true
and the message “Valid email address” will be displayed. If the email address does not match the pattern, the test()
method will return false
and the message “Invalid email address” will be displayed.
It’s important to note that this is a basic example and there are many variations of email addresses that are considered valid. So this regular expression may not be able to validate all email addresses.
A more robust way to validate an email address is to use a library like “email-validator” which has better support for different types of email addresses.
const validator = require("email-validator");
if (validator.validate(email)) {
console.log("Valid email address");
} else {
console.log("Invalid email address");
}
You can also use these libraries and regular expression together to make sure that email address is in correct format and also exist on the email server.
It’s worth noting that, the best way to check if an email address is valid is to send a verification email to the address and have the user click on a link to confirm they own it.
Also Read:
0 Comments