ASP.NET Core 2: Model Validation Part 2

download.jpgIn Part 1, we covered simple model validation where the entire model is posted back in a form.

In this tutorial, we cover how to validate just one field on the server as well.

Create a simple Model, on this class we have a National ID field. The possible values for this ID are too many to store or calculate on the client so need to be verified on the server without posting the entire form back.

public class PersonModel
    public int NationalID { getset; }

On the Controller add a VerifyNationalID method on the Home controller:

public class HomeController : Controller
    public IActionResult Index()
        return View(new PersonModel());
    public IActionResult VerifyNationalID(int nationalId)
        if (nationalId == 12345) return new JsonResult(true);
        return new JsonResult("That ID does not exist in the database");

On the client add a simple text box and submit button. Use the TagHelpers to connect to the model’s NationalID field

<!-- Add the validation scripts-->
<script src=""></script>
<script src=""></script>
<script src=""></script>
<form action="/Home/VerifyEntireForm" method="post">
    <div class="form-group">
        <label asp-for="NationalID" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="NationalID" class="form-control" />
            <span asp-validation-for="NationalID" class="text-danger"></span>
    <button type="submit" class="btn btn-primary">Submit</button>

When run, a warning will appear when the user leaves the field. The plumbing is handled by jQuery and ASP.NET CORE.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s