Validation is a method to authenticate the user. JavaScript provides the facility to validate the form on the client-side so data processing will be faster than server-side validation.
Email Validation in JavaScript – Step by Step
Validating email is a very important point while validating an HTML form. An email is a string or a subset of ASCII characters that are separated into two parts by “@” symbol.
The first part can consist of the following ASCII Characters:
- Uppercase (A-Z) and lowercase (a-z) letters
- Digits (0-9)
- Characters such as ! # $ % & ‘ * + – / = ? ^ _ ` { | } ~
- Character . ( period, dot or fullstop) but it should not be the first or last character and should not come one after the other
Email-Validation.js
function ValidateEmail(inputText)
{
var mailformat = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;
if(inputText.value.match(mailformat))
{
alert("You have entered a valid email address!"); //The pop up alert for a valid email address
document.form1.text1.focus();
return true;
}
else
{
alert("You have entered an invalid email address!"); //The pop up alert for an invalid email address
document.form1.text1.focus();
return false;
}
}
Email-validation.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript email validation</title>
<link rel='stylesheet' href='form-style.css' type='text/css' /> //link to the source file of css to add styles
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Enter email to Validate</h2>
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li> </li>
<li class="Validate"><input type="submit" name="Validate" value="Validate" onclick="ValidateEmail(document.form1.text1)"/></li> //Adding the submit button
<li> </li>
</ul>
</form>
</div>
<script src="email-validation.js"></script> //link to the source file of javascript function
</body>
</html>
Email-Validation.css
li {list-style-type: none;
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 800px;
background : rgb(153, 198, 211);
border: 1px soild rgb(1, 20, 24);
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 20pt;
}
input:focus, textarea:focus{
background-color: lightyellow;
}
input submit {
font-size: 10pt;
}