In this article I will explain with an example, how to validate Email using JavaScript and Regular Expression (Regex) in ASP.Net Core MVC.
When the Submit Button is clicked, the Email Address in the TextBox will be validated using JavaScript and Regular Expression (Regex) in ASP.Net Core MVC.
Controller
The Controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
View
The View consists of an HTML TextBox, SPAN element and a Button.
The Submit Button has been assigned a JavaScript OnClick event handler which calls the ValidateEmail JavaScript function.
When the Submit Button is clicked, the Email Address in the TextBox will be validated using JavaScript and Regular Expression (Regex) and if the Email Address is invalid, the error message will be displayed next to the TextBox.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<input type="text" id="txtEmail" />
<span id="lblError" style=" color:red"></span>
<br />br />
<input type="button" id="btnValidate" value="Submit" onclick="ValidateEmail()" />
<script type="text/javascript">
function ValidateEmail() {
var email = document.getElementById("txtEmail").value;
var lblError = document.getElementById("lblError");
lblError.innerHTML = "";
var expr = /^([\w-\.]+)@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!expr.test(email)) {
lblError.innerHTML = "Invalid email address.";
}
}
</script>
</body>
</html>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Downloads