Forms Validation in ASP.NET Core Razor Pages

On the Visual Studio, create new ASP.NET Core Web Application project

Select Empty Template

Click Ok button to Finish




Open Startup.cs file and add new configurations as below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreRazorPagesWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

Select Views folder and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select Razor View Imports item and click Add button to Finish

In _ViewImports.cshtml file and TagHelpers library as below:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers




Create new folder named Models. In Models folder, create new entities class as below:

Create new class named Account.cs as below:

using System.ComponentModel.DataAnnotations;

namespace LearnASPNETCoreRazorPagesWithRealApps.Entities
{
    public class Account
    {
        [Required]
        [MinLength(3)]
        [MaxLength(10)]
        public string Username { get; set; }

        [Required]
        [RegularExpression("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})")]
        public string Password { get; set; }

        [Range(18, 120)]
        public int Age { get; set; }

        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Url]
        public string Website { get; set; }
    }
}

Create new folder named Pages. In this folder, create new Razor Page named Index as below:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using LearnASPNETCoreRazorPagesWithRealApps.Entities;

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class IndexModel : PageModel
    {
        [BindProperty]
        public Account account { get; set; }

        public void OnGet()
        {
            account = new Account();
        }

        public IActionResult OnPost(Account account)
        {
            if (account.Username != null && account.Username.Equals("abc"))
            {
                ModelState.AddModelError("account.Username", "Username Already Exists");
            }

            if (!ModelState.IsValid)
            {
                return Page();
            }
            else
            {
                return RedirectToPage("Success");
            }
        }
    }
}




@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.IndexModel
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="~/style.css" rel="stylesheet" type="text/css" />
</head>
<body>

    <form method="post" asp-page="index">
        <table>
            <tr>
                <td>Username</td>
                <td>
                    <input asp-for="@Model.account.Username" />
                </td>
                <td>
                    <span asp-validation-for="@Model.account.Username" class="error"></span>
                </td>
            </tr>
            <tr>
                <td>Password</td>
                <td>
                    <input type="password" asp-for="@Model.account.Password" />
                </td>
                <td>
                    <span asp-validation-for="@Model.account.Password" class="error"></span>
                </td>
            </tr>
            <tr>
                <td>Age</td>
                <td>
                    <input asp-for="@Model.account.Age" />
                </td>
                <td>
                    <span asp-validation-for="@Model.account.Age" class="error"></span>
                </td>
            </tr>
            <tr>
                <td>Email</td>
                <td>
                    <input asp-for="@Model.account.Email" />
                </td>
                <td>
                    <span asp-validation-for="@Model.account.Email" class="error"></span>
                </td>
            </tr>
            <tr>
                <td>Website</td>
                <td>
                    <input asp-for="@Model.account.Website" />
                </td>
                <td>
                    <span asp-validation-for="@Model.account.Website" class="error"></span>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="Save" />
                </td>
            </tr>
        </table>
    </form>

</body>
</html>

In Pages folder, create new Razor Page named Success as below:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class SuccessModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.SuccessModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Success</title>
</head>
<body>

    <h3>Success Page</h3>

</body>
</html>




Open Index Razor Page with following url: http://localhost:1115

Click Save button submit form to OnPost action in Index razor page with invalid data as below:

Click Save button submit form to OnPost action in Index razor page with valid data

Output