Forms Validation in ASP.NET Core MVC 5

On the Visual Studio, select Create a new project from Get Started

Select ASP.NET Core Web Application




Input Project Name and select Location for new project

Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create 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;
using Microsoft.Extensions.Hosting;

namespace LearnASPNETCoreMVC5
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

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

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Demo}/{action=Index}/{id?}");
            });
        }
    }
}

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 LearnASPNETCoreMVC5.Models
{
    public class Account
    {
        [Required]
        [MinLength(3)]
        [MaxLength(10)]
        public string Username
        {
            get;
            set;
        }

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


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

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

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




Create new folder named Controllers. In this folder, create new controller named AccountController.cs as below:

using LearnASPNETCoreMVC5.Models;
using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCoreMVC5.Controllers
{
    [Route("account")]
    public class AccountController : Controller
    {
        [Route("")]
        [Route("index")]
        [Route("~/")]
        public IActionResult Index()
        {
            return View("Index", new Account());
        }

        [Route("save")]
        [HttpPost]
        public IActionResult Save(Account account)
        {
            if (ModelState.IsValid)
            {
                ViewBag.account = account;
                return View("Success");
            }
            else
            {
                return View("Index");
            }
        }
    }
}

Create new folder named Views. In this folder, create new folder named Account and add new views as below:

In Account folder, create new view named Index.cshtml as below:

@model LearnASPNETCoreMVC5.Models.Account

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

    <h3>Register Page</h3>
    <form asp-controller="account" asp-action="save" method="post">
        <table border="0" cellpadding="2" cellspacing="2">
            <tr>
                <td>Username</td>
                <td>
                    <input asp-for="Username" />
                </td>
                <td>
                    <span asp-validation-for="Username"></span>
                </td>
            </tr>
            <tr>
                <td>Password</td>
                <td>
                    <input asp-for="Password" type="password" />
                </td>
                <td>
                    <span asp-validation-for="Password"></span>
                </td>
            </tr>
            <tr>
                <td>Age</td>
                <td>
                    <input asp-for="Age" />
                </td>
                <td>
                    <span asp-validation-for="Age"></span>
                </td>
            </tr>
            <tr>
                <td>Email</td>
                <td>
                    <input asp-for="Email" />
                </td>
                <td>
                    <span asp-validation-for="Email"></span>
                </td>
            </tr>
            <tr>
                <td>Website</td>
                <td>
                    <input asp-for="Website" />
                </td>
                <td>
                    <span asp-validation-for="Website"></span>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="Save" />
                </td>
            </tr>
        </table>
    </form>

</body>
</html>




In Account folder, create new view named Success.cshtml as below:

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

    <h3>Account Info</h3>
    <table cellpadding="2" cellspacing="2" border="1">
        <tr>
            <td>Username</td>
            <td>@ViewBag.account.Username</td>
        </tr>
        <tr>
            <td>Password</td>
            <td>@ViewBag.account.Password</td>
        </tr>
        <tr>
            <td>Age</td>
            <td>@ViewBag.account.Age</td>
        </tr>
        <tr>
            <td>Email</td>
            <td>@ViewBag.account.Email</td>
        </tr>
        <tr>
            <td>Website</td>
            <td>@ViewBag.account.Website</td>
        </tr>
    </table>

</body>
</html>

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




Access Index action in Account controller with following url: http://localhost:9596/Account/Index

Output

Click Save button submit form to Save action in Account controller with invalid data as below:

Click Save button submit form to Save action in Account controller with valid data

Output