当其他属性应用于类时,CustomValidationAttribute不起作用

时间:2011-02-23 12:58:44

标签: validation .net-4.0 data-annotations validationattribute

繁殖:

Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Module Module1

  Sub Main()
    Dim type = GetType(Contact)
    TypeDescriptor.AddProviderTransparent(
      New AssociatedMetadataTypeTypeDescriptionProvider(type), type)


    Dim contact As New Contact
    Dim context As New ValidationContext(contact, Nothing, Nothing)
    Dim errors As New List(Of ValidationResult)
    Dim result = Validator.TryValidateObject(contact, context, errors, True)
  End Sub
End Module

<CustomValidation(GetType(Contact.ContactMd), "*********************")>
<MetadataType(GetType(Contact.ContactMd))>
Public Class Contact

  Public Property Email As String
  Public Property EmailRepeat As String

  Public Class ContactMd

    '<Required()>
    Public Property Email
    '<Required()>
    Public Property EmailRepeat

    Public Shared Function ValidateEmails(ByVal contact As Contact) _
        As ValidationResult
      Return If(contact.Email = contact.EmailRepeat,
                ValidationResult.Success,
                New ValidationResult("Fail!"))
    End Function
  End Class
End Class

以上代码将引发异常:
The CustomValidationAttribute method '*********************' does not exist in type 'ContactMd' or is not public and static.

这个例外是合理的,这表明事情正在发挥作用。 一旦我取消了Md类中属性的Required属性,就不会抛出异常,这意味着验证系统不会对属性类型属性和类级属性进行验证。

任何解决方法?

2 个答案:

答案 0 :(得分:0)

答案是,验证系统首先验证属性验证属性(在这种情况下为Required属性),并且只有在对象传递属性属性时才会进入CustomValidationAttribute。 / p>

所以根据上面的复制,更改行

Dim contact As New Contact
等等(允许enitity传递属性验证):

Dim contact As New Contact With { .Email = "*", .EmailRepeat = "*" }

将抛出预期的异常。

答案 1 :(得分:0)

CustomValidationAttribute指定的方法的签名必须是:

VB:

Public Shared Function OnValidate(
    entity As Contact, context As ValidationContext) As ValidationResult

C#:

public static ValidationResult OnValidate(Contact entity, ValidationContext context)

如果验证正常,则应返回ValidationResult.Success。