RequiredAttribute Class
Updated: July 2008
Specifies that a data field value is required.
Assembly: System.ComponentModel.DataAnnotations (in System.ComponentModel.DataAnnotations.dll)
By applying the RequiredAttribute attribute to the data field, you can override the database schema rule that allows a data field to be empty.
When you apply this attribute to a data field you must follow the guidelines for the use of the validation attributes. For more information, see ASP.NET Dynamic Data Guidelines.
The following example uses the RequiredAttribute attribute to override the database schema rule that allows a data field to be empty. The example performs the following steps:
Implements a metadata partial class and the associated metadata class.
In the associated metadata class, it applies the RequiredAttribute attribute, which specifies the following requirements:
The Title data field cannot be empty. If validation fails, the code in the example throws a validation exception and displays an error message. The error message is specified at the time that the attribute is applied to the data field.
The MiddleName data field cannot be empty. If validation fails, the code in the example throws a validation exception and displays an error message.
using System; using System.Web.DynamicData; using System.ComponentModel.DataAnnotations; using System.Globalization; [MetadataType(typeof(CustomerMetaData))] public partial class Customer { } public class CustomerMetaData { // Require that the Title is not null. // Use custom validation error. [Required(ErrorMessage = "Title is required.")] public object Title; // Require that the MiddleName is not null. // Use standard validation error. [Required()] public object MiddleName; }
System.Attribute
System.ComponentModel.DataAnnotations.ValidationAttribute
System.ComponentModel.DataAnnotations.RequiredAttribute
Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.