Forms Validation in ASP.NET Core MVC


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

Select Empty Template

Click Ok button to Finish

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

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

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

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Account}/{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;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace LearnASPNETCoreMVCWithRealApps.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 System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LearnASPNETCoreMVCWithRealApps.Models;
using Microsoft.AspNetCore.Mvc;

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

        [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 razor views as below:

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

@{
    Layout = null;
}

@model LearnASPNETCoreMVCWithRealApps.Models.Account

<!DOCTYPE html>

<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:

@{
    Layout = null;
}

<!DOCTYPE html>

<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

I recommend you refer to the books below to learn more about the knowledge in this article: