asp.net-mvc RequiredAttribute


Example

The Required attribute specifies that a property is required. An error message can be specified on using the ErrorMessage property on the attribute.

First add the namespace:

using System.ComponentModel.DataAnnotations;

And apply the attribute on a property.

public class Product
{
   [Required(ErrorMessage = "The product name is required.")]
   public string Name { get; set; }

   [Required(ErrorMessage = "The product description is required.")]
   public string Description { get; set; }
}

It is also possible to use resources in the error message for globalized applications. In this case, the ErrorMessageResourceName must be specified with the resource key of the resource class (resx file) that must be setted on the ErrorMessageResourceType:

public class Product
{
   [Required(ErrorMessageResourceName = "ProductNameRequired", 
             ErrorMessageResourceType = typeof(ResourceClass))]
   public string Name { get; set; }

   [Required(ErrorMessageResourceName = "ProductDescriptionRequired", 
             ErrorMessageResourceType = typeof(ResourceClass))]
   public string Description { get; set; }
}