HTML Form - Email Validation with JavaScript
Email validation is very important in HTML forms. Here we have discussed how to validate email addresses using JavaScript. Parts of an email address An email address is a unique identifier of an email account bound to a domain server. An email address has two main parts. The two main parts are:- Username.
- Domain name
How to validate Email address using JavaScript?
The complete code at the end of page has 3 different parts. They are- HTML Form
- JavaScript Code
- Regular Expression (JavaScript)
<!-- HTML Form - Validate Email Address --> <form> <input id="email" type="text" placeholder="Enter your email id" /> <button type="button">Submit</button> </form>Now, we will write emailValidate() function in javascript. On the ‘onClick’ attribute of the button we will call this function. 2. Javascript Email Validation Function In the emailValidate() JavaScript function, we parse the email id in textbox by the method ‘getElementById’. This email address is cross verified for a pattern with regular expression.
function validate()
{ var text = document.getElementById("email").value;
now, we are creating a new variable called ‘reg’ to store the pattern of the email address to check for its validity.
3.Email Format Regular Expression:
This regular expression pattern will determine if the email address is in proper format or not.
var reg = /^([a-zA-Z0-9\.-]+)@([a-z0-9-]+).([a-z]{2,8})(.[a-z]{2,8})?$/
This regular expression verifies each part of email, ie. Username and domain name in one go.
- The first part containing [a-zA-z0-9\.-] checks for lowercase, uppercase, numbers, (.)dots and hypens and the ‘+’ means that there can be any number of characters.
- Separated by ‘@’ symbol, then for the domain name part we will check for [a-zA-z0-9] and again a ‘+’ sign for any number of characters.
- Again, separated by the ‘.’
<!DOCTYPE html>
<html lang="en">
<head>
<title>Email validation</title>
<script>
function validate()
{
var text = document.getElementById("email").value;
var reg = /^([a-zA-Z0-9\.-]+)@([a-z0-9-]+).([a-z]{2,8})(.[a-z]{2,8})?$/
if(reg.test(text) == false)
{
alert("Invalid email address");
}
else
{
alert("Valid email address");
}
}
</script>
</head>
<body>
<form>
<input type="text" id="email" placeholder="Enter your email id">
<button type="button">Submit</button>
</form>
</body>
</html>
Test the code code by entering different pattern of email ids.
External Reference: Also read this page which discuss about similar process of Email validation using JavaScript.