Export (0) Print
Expand All

RequiredAttribute Class

Updated: July 2008

Specifies that a data field value is required.

Namespace:  System.ComponentModel.DataAnnotations
Assembly:  System.ComponentModel.DataAnnotations (in System.ComponentModel.DataAnnotations.dll)

[AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field, AllowMultiple = false)]
public class RequiredAttribute : ValidationAttribute

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.Object
  System.Attribute
    System.ComponentModel.DataAnnotations.ValidationAttribute
      System.ComponentModel.DataAnnotations.RequiredAttribute

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

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.

.NET Framework

Supported in: 3.5 SP1

Date

History

Reason

July 2008

Added topic for new class.

SP1 feature change.

Community Additions

ADD
Show:
© 2014 Microsoft