PROWAREtech

articles » current » javascript » validate-email

JavaScript: Validate Email Address Using Regular Expressions

How to validate email addresses by checking their format using client-side code.

There are many allowed characters that many email providers do not allow in their email addresses.

This regular expression should cover most if not all emails addresses (note: it does not allow the "/" character unless inside quotes):


var emailrgx = /^(([^<>()[\]\\\/.,;:\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,}))$/;

This regular expression allows the "/" character:


var emailrgx = /^(([^<>()[\]\\.,;:\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,}))$/;

Here is an example HTML document using the first regular expression.


<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Validate Email</title>
</head>
<body>
	<p>Enter email address; if red then it is not valid.</p>
	<form id="form">
		<input type="text" name="email" placeholder="email..." />
	</form>
	<script type="text/javascript">
		var emailrgx = /^(([^<>()[\]\\\/.,;:\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,}))$/;
		var form = document.getElementById("form");
		form.email.addEventListener("keyup", function(event) {
			var target = event.target;
			if (target.value.length == 0 || target.value.match(emailrgx)) {
				target.style.color = "";
			}
			else {
				target.style.color = "red";
			}
		});
	</script>
</body>
</html>

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT