Using Data Annotations for Model Validation
We can easily add validation to our application by adding Data Annotations to our
model classes. Data Annotations allow us to describe the rules we want applied to
our model properties, and ASP.NET MVC will take care of enforcing them and
displaying appropriate messages to our users.
Adding Validation to any Application
Some of Data Annotation attributes:
Required – Indicates that the property is a required field
DisplayName – Defines the text we want used on form fields and validation
messages
StringLength – Defines a maximum length for a string field
Range – Gives a maximum and minimum value for a numeric field
Bind – Lists fields to exclude or include when binding parameter or form values
to model properties
ScaffoldColumn – Allows hiding fields from editor forms
Note: For more information on Model Validation using Data Annotation attributes, see
the MSDN documentation at https://go.microsoft.com/fwlink/?LinkId=159063
using System.ComponentModel; These lines of code
using System.ComponentModel.DataAnnotations; (namespaces) must be
using System.Web.Mvc; added on your model /
class.
public class ProductModel
{
[Required(ErrorMessage = "Please enter product category")]
[DisplayName("Product Category")]
public string category { get; set; }
[Required(ErrorMessage = "Please enter product name")]
[DisplayName("Product Name")]
[StringLength(20)]
public string productName { get; set; }
[Required(ErrorMessage = "Please enter product name")]
[DisplayName("Product Name")]
[StringLength(20)]
public string productDesc { get; set; }
public int quantity { get; set; }
[Range(50,300)]
public double price { get; set; }
public string prodAvailability { get; set; }
public string ExtraCap { get; set; }
public string ExtraCard { get; set; }