In this article I will explain with an example, how to validate Email using JavaScript and Regular Expression (Regex) in ASP.Net Core Razor Pages.
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 Razor Pages.
 
 
Razor PageModel (Code-Behind)
The PageModel consists of following Handler method.
Handler method for handling GET operation
This Handler method handles the GET calls, for this particular example it is not required and hence left empty.
public class IndexModel : PageModel
{
    public void OnGet()
    {
    }
}
 
 
Razor Page (HTML)
The HTML of Razor Page 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.
@page
@model Validate_Email_JavaScript_Razor_Core.Pages.IndexModel
@{
    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
ASP.Net Core Razor Pages: Email Validation using JavaScript and Regular Expression
 
 
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads