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

ASP.NET Core 2: Model Validation Part 1

download.jpgIn this tutorial, we’ll show you how to add some simple custom business logic to a model so that values can be verified on the server via a post back.

Business Logic: Only children are allowed in this model. A child is under 13.

Our Model is simple and has a ChildOnly attribute which we’ll create next:

public class PersonModel
{
    [ChildOnly] 
    public int Age { getset; }
}

Next we create the business logic-holding attribute. The function IsValid() is what is called by ASP.NET Core’s validation system and is fairly simple:

public class ChildOnlyAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //Get the model we are trying to validate
        if (validationContext?.ObjectInstance is PersonModel model)
        {
            //Only Kids are allowed (under 13)
            if (model.Age > 12)
            {
                return new ValidationResult("Person is too old and is not considered a child");
            }
        }
        return ValidationResult.Success;
    }
}

Now that we have the model and the business logic ready on the server, let’s add some simple HTML. The TagHelpers will convert the purple commands into properly bound HTML.

<form action="/Home/Verify" method="post">
    <div class="form-group">
        <label asp-for="Age" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="Age" class="form-control" />
            <span asp-validation-for="Age" class="text-danger"></span>
        </div>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

On our controller we have the Actions to both present the form and verify it on a post back.

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View(new PersonModel());
    }
 
    public IActionResult Verify(PersonModel model)
    {
        if (!ModelState.IsValid)
        {
            return View("Index",model);
        }
        return new ContentResult()
        {
            Content = "Looks Good"
        };
    }

Here’s what it looks like when run:

home verify.png