Email validation in JavaScript

Using regular expression: Enter email here

Userid part ( before @ char )

  • Uppercase and lowercase letters (A-Z and a-z)
  • Numeric characters (0-9)
  • Special characters - ! # $ % & ' * + - / = ? ^ _ { | } ~`
  • Period, dot, or full stop (.) with the condition that it cannot be the first or last letter of the email and cannot repeat one after another.

Domain Part ( after @ )

  • Letters
  • Digits
  • Hyphens
  • Dots
Source code is here ( Ignore the CSS to manage the color of the message )
<script>
function validateEmail() {
email=document.getElementById('t1').value
var regex=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

//alert(regex.test(email)); // get true or false as alert message 
var msg = document.getElementById("msg");
if(regex.test(email)){
msg.classList.remove("alert-danger");
 msg.classList.add("alert-success");	
 msg.innerHTML='Correct'
}else{
msg.classList.remove("alert-success");
msg.classList.add("alert-danger");
msg.innerHTML='NOT Correct'
}
}
</script>
HTML part to display the input box , button and message area.
<div class='row'> <div class='col-md-4 col-md-offset-1'>
<input type=text class='form-control' id=t1 name=t1>
</div><div class='col-md-2'><input type=submit onClick='validateEmail()'></div>
<div class='col-md-4'> <div id='msg' class='alert alert-primary' role='alert'> Message </div> 
 </div></div>

Presence of @ and .

The input string must have two minimum chars . One is @ and other one is presence of . ( dot ).

To ensure this, we will use indexOf function. If both are present then the function will return true so the form will be submitted otherwise it will return false.
Demo of email validation
Source code is here
<html>
<head>
<title></title>
</head>
<body >
<script type="text/javascript" >
function check_form(){
var em=document.getElementById('em').value;
if(em.indexOf("@") < 1 || em.indexOf(".") < 1 ) 
{
alert('Please check your email address');
 return false;
 }
alert('Email validation passed, you will be taken to tutorial page');
return true;
}
</script>

<form method=post action='email-validation.php' onsubmit='return check_form()'; name='myForm'>
<input type=text name=em id='em'><input type=submit value=Submit>
</form>

</body>
</html>

JavaScript Validation
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer