What is JavaScript Validation?
JavaScript is use to check the entered email address is valid or not before store E-Mail address into a server.
JavaScript E-Mail Validation
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript E-Mail Validation</title>
</head>
<body>
<script type="text/javascript">
function validate(form_id, email) {
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.forms[form_id].elements[email].value;
if(reg.test(address) == false) {
alert('Invalid Email Address');
return false;
}
}
</script>
<form id="form_id" method="post" action="form_submit_message.php" onsubmit="javascript:return validate('form_id', 'email');">
Enter Your Email Address:
<input type="text" id="email" name="email" size="35"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Example Result
JavaScript E-Mail Validation 2
Lets see another validation logic to validate E-Mail Address.
Syntax
function validate_required(field_condition, alert_Message) {
with (field_condition) {
if (value==null||value=="") {
alert(alert_Message);return false;
} else {
return true;
}
}
}
Logic Condition
function validate_email(field_condition, alert_message) {
with (field_condition) {
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
if (apos<1||dotpos-apos<2) {
alert(alert_message);
return false;
} else {
return true;
}
}
}
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript E-Mail Validation</title>
</head>
<body>
<script type="text/javascript">
function validate_email(field_condition, alert_message) {
with(field_condition) {
apos = value.indexOf("@");
dotpos = value.lastIndexOf(".");
if (apos < 1 || dotpos - apos < 2) {
alert(alert_message);
return false;
} else {
return true;
}
}
}
function validate_form(form) {
with(form) {
if (validate_email(email, "This E-Mail Address is not a valid!") == false) {
email.focus();
return false;
}
}
}
</script>
<form action="form_submit_message.php" onsubmit="return validate_form(this);" method="post">
Enter Your Email:
<input type="text" name="email" size="35"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Example Result