It is very important to validate the email while validating an HTML form. An email is taken as a string which is separated into two parts by the @ symbol.
1. user_info
2. a domain
i.e., user_info@domain.
The length of the user_info part may be up to 64 characters long and domain name may be up to 253 characters.
The personal_info part contains the following ASCII characters.:
- Digits (0-9).
- Uppercase (A-Z) and lowercase (a-z) English letters.
- Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
- Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.
The domain name [for example com, org, net, in, us, info] part contains letters, digits, hyphens and dots.
JavaScript code to validate an email id:
function ValidateEmail(mail)
{
if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddress.value))
{
return(true)
}
alert("You have entered an invalid email address!")
return(false)
}
we have used a regular expression /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ to get a valid email id.
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>Email Validation using JavaScript</title>
<link rel='stylesheet' href='form_style.css' type='text/css'/>
</head>
<body onload='document.form.text_email.focus()'>
<div class=email>
<form name = form action = #>
<ul>
<li><input type =text name =text_email/></li>
<li class=submit><input type=submit name=submit value=submit
onclick=ValidateEmail(document.from.text_email)/></li>
</pre> </ul>
</from>
</div>
<script src=email_validate.js></script>
</body>
</html>
JavaScript Code:
function ValidateEmail(inputText)
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.value.match(mailformat))
{
document.form.text_email.focus();
return true;
}
else
{
alert("Invalid email address!");
document.form.text_email.focus()
return false;
}
}
CSS Code:
li{list-style-type: none;font-size: 16pt;}
.mail{margin: auto; padding-top: 10px; padding-bottom: 10px; width: 400px;
background : #D8F1F8; border: 1px soild silver;}
input {font-size: 20pt;}
input:focus, textarea:focus{background-color: grey;}
input submit{font-size: 12pt;}
0 Comment(s)