Configuring and using validation
In this recipe, you will learn how to configure and use client-side validation with jQuery, and server-side validation with C#.
Getting ready
We will create an ASP.NET Core MVC Web Application template by going to File | New | Project | AspNet Core Web Application.
How to do it...
- First of all, let's create a class with validation attributes. These attributes will be used on both the client side and the server side:
public class ProductViewModel
{
public int Id { get; set; }
[Required]
[RegularExpression(@"^[a-zA-Z]{1,40}$",
ErrorMessage = "The field must be a string")]
public string Name { get; set; }
[Required]
[Range(0.01, double.MaxValue,
ErrorMessage = "Please enter a positive number")]
public decimal Price { get; set; }
}- In addition to this, we will create a form in order to post the
ProductViewModel. This is theFormversion ofTagHelpers:
<form asp-controller="Home" asp-action="AddProduct" method="post" asp-antiforgery="true"> ...