In this article we will discuss, how to check client side validation for email address using JavaScript in asp.net MVC. It is common to check the format of the email is valid or not. To validate email address we need to use regular expression. In MVC razor we should use @@ symbol to perform validation.
var emailRegEx = /^(([^<>()[\]\\.,;:\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,}))$/;
Normal Html:
For normal we should use @ symbol to perform validation
var emailRegEx = /^(([^<>()[\]\\.,;:\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,}))$/;
Email : <input type="text" id="txtEmail" onkeyup="validateEmail()" />
<script type="text/javascript">
function validateEmail()
{
var emailTextBox = document.getElementById("txtEmail");
var email = emailTextBox.value;
var emailRegEx = /^(([^<>()[\]\\.,;:\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,}))$/;
emailTextBox.style.color = "white";
if (emailRegEx.test(email))
{
emailTextBox.style.backgroundColor = "green";
}
else
{
emailTextBox.style.backgroundColor = "red";
}
}
</script>
Output:
Invalid email address:
Valid email address: