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

 

Advertisements

One thought on “ASP.NET Core 2: Model Validation Part 1

  1. Pingback: ASP.NET Core 2: Model Validation Part 2 | Xamarin and Visual Studio for Beginners

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