Unable to set membernames from custom validation attribute in MVC2

后端 未结 4 2212
甜味超标
甜味超标 2020-12-11 17:04

I have created a custom validation attribute by subclassing ValidationAttribute. The attribute is applied to my viewmodel at the class level as it needs to validate more tha

4条回答
  •  时光取名叫无心
    2020-12-11 17:18

    When returning the validation result use the two parameter constructor. Pass it an array with the context.MemberName as the only value. Hope this helps

    
    
    
    Public Class NonNegativeAttribute
    Inherits ValidationAttribute
    Public Sub New()
    
    
    End Sub
    Protected Overrides Function IsValid(num As Object, context As ValidationContext) As ValidationResult
        Dim t = num.GetType()
        If (t.IsValueType AndAlso Not t.IsAssignableFrom(GetType(String))) Then
    
            If ((num >= 0)) Then
                Return ValidationResult.Success
            End If
            Return New ValidationResult(context.MemberName & " must be a positive number",     New String() {context.MemberName})
    
        End If
    
        Throw New ValidationException(t.FullName + " is not a valid type. Must be a number")
    End Function
    
    End Class
    

提交回复
热议问题