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
{
    [Remote"VerifyNationalID""Home")] 
    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="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.0.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></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>
        </div>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

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

validation2.png

 

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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