Compartir a través de


CustomValidationAttribute Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Designates a customized method to execute to validate the entity member.

Inheritance Hierarchy

System.Object
  System.Attribute
    System.ComponentModel.DataAnnotations.ValidationAttribute
      System.ComponentModel.DataAnnotations.CustomValidationAttribute

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

Syntax

'Declaration
<AttributeUsageAttribute(AttributeTargets.Class Or AttributeTargets.Method Or AttributeTargets.Property Or AttributeTargets.Field Or AttributeTargets.Parameter, AllowMultiple := True)> _
Public NotInheritable Class CustomValidationAttribute _
    Inherits ValidationAttribute
[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Method|AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter, AllowMultiple = true)]
public sealed class CustomValidationAttribute : ValidationAttribute

The CustomValidationAttribute type exposes the following members.

Constructors

  Name Description
Public method CustomValidationAttribute Initializes a new instance of the CustomValidationAttribute class.

Top

Properties

  Name Description
Public property ErrorMessage Gets or sets the non-localizable error message to display when validation fails. (Inherited from ValidationAttribute.)
Public property ErrorMessageResourceName Gets or sets the property name on the resource type that provides the localizable error message. (Inherited from ValidationAttribute.)
Public property ErrorMessageResourceType Gets or sets the resource type that provides the localizable error message. (Inherited from ValidationAttribute.)
Protected property ErrorMessageString Gets the localized or non-localized error message. (Inherited from ValidationAttribute.)
Public property Method Gets the name of the method to invoke for validation.
Public property ValidatorType Gets the type that contains the method for validating the member.

Top

Methods

  Name Description
Public method Equals Infrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public method FormatErrorMessage Applies formatting to an error message based on the data field where the error occurred. (Overrides ValidationAttribute.FormatErrorMessage(String).)
Public method GetHashCode Returns the hash code for this instance. (Inherited from Attribute.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method GetValidationResult Determines whether the specified object is valid and returns an object that includes the results of the validation check. (Inherited from ValidationAttribute.)
Protected method IsValid Determines whether the specified object is valid. (Inherited from ValidationAttribute.)
Public method Match When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Public method Validate Determines whether the specified object is valid and throws a ValidationException if the object is not valid. (Inherited from ValidationAttribute.)

Top

Remarks

You apply the CustomValidationAttribute attribute to an entity or one of its members when you need to specify a method to use for validating the entity or the value of the member. The CustomValidationAttribute attribute can be used with a method as an alternative to deriving a class from ValidationAttribute. The CustomValidationAttribute attribute can be applied to a class, property, field, method, or parameter.

The type supplied for the ValidatorType property must be marked as public in C# or Public in Visual Basic.

The method specified in the Method property must be public and static in C#, or Public and Shared in Visual Basic. The specified method must return a ValidationResult object that equals Success if the value is valid, or contains an error message if the value is not valid.

The validation method must contain at least one input parameter for the value to validate. The value parameter can be strongly typed. If an object of a different type is passed in the method, the CustomValidationAttribute class attempts to convert the passed value to the specified type before executing the validation method. The method may also accept a ValidationContext object to provide additional information about the validation request. The following examples show the allowed signatures in C# and Visual Basic.

public static ValidationResult MethodName(object value) {...}
public static ValidationResult MethodName(object value, ValidationContext context) {...}
Public Shared Function MethodName(value As Object) As ValidationResult
Public Shared Function MethodName(value As Object, context As ValidationContext) As ValidationResult

Examples

The first example shows how to apply the CustomValidationAttribute attribute to an entity member named SalesPerson and an entity class named CustomerAddress. The specified method named ValidateSalesPerson is executed when a value is applied to the SalesPerson property and the method named ValidateAddress is executed when values are applied to the CustomerAddress class.

Public Class Customer
  <CustomValidation(GetType(AWValidation), "ValidateSalesPerson")> _
  Public Property SalesPerson As String
    'Implement Get and Set logic
  End Property
End Class

<CustomValidation(GetType(AWValidation), "ValidateAddress")> _
Public Class CustomerAddress
  ' Provide properties.
End Class
public class Customer
{
  [CustomValidation(typeof(AWValidation), "ValidateSalesPerson")]
  public string SalesPerson { get; set; }
}

[CustomValidation(typeof(AWValidation), "ValidateAddress")]
public class CustomerAddress
{
  // Provide properties.
}

The second example shows the validation type and methods for validating the entity member and entity class. The parameters for the validation methods are strongly-typed. ValidateSalesPerson takes a string value containing the name of the sales person to apply to the property. ValidateAddress takes an instance of the CustomerAddress class.

Imports System.ComponentModel.DataAnnotations

Public Class AWValidation
  Public Shared Function ValidateSalesPerson(salesPerson As String) As ValidationResult
    Dim isValid As Boolean

    ' Perform validation logic here and set isValid to true or false.

    If (IsValid) Then
      ValidateSalesPerson = ValidationResult.Success
    Else
      ValidateSalesPerson = New ValidationResult( _
          "The selected sales person is not available for this customer.")
    End If
    End Function

  Public Shared Function ValidateAddress(addressToValidate As CustomerAddress) As ValidationResult
    Dim isValid As Boolean

    ' Perform validation logic here and set isValid to true or false.

    If (IsValid) Then
      ValidateAddress = ValidationResult.Success
    Else
      ValidateAddress = New ValidationResult( _
          "The address for this customer does not match the required criteria.")
    End If
  End Function
End Class
using System.ComponentModel.DataAnnotations;

public class AWValidation
{
  public static ValidationResult ValidateSalesPerson(string salesPerson)
  {
    bool isValid;

    // Perform validation logic here and set isValid to true or false.

    if (isValid)
    {
      return ValidationResult.Success;
    }
    else
    {
      return new ValidationResult(
          "The selected sales person is not available for this customer.");
    }
  }

  public static ValidationResult ValidateAddress(CustomerAddress addressToValidate)
  {
    bool isValid;

    // Perform validation logic here and set isValid to true or false.

    if (isValid)
    {
      return ValidationResult.Success;
    }
    else
    {
      return new ValidationResult(
          "The address for this customer does not match the required criteria.");
    }
  }
}

Version Information

Silverlight

Supported in: 5, 4, 3

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

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