User-1270389142 posted
Hi Guys,
I foudn the answer by myself. Below is my code, if anyone is interested:
ValidationAttribute class:
Imports system.Reflection
<AttributeUsage(AttributeTargets.Property, Inherited:=True, AllowMultiple:=True)> _
Public Class ValidationAttribute
Inherits Attribute
Public Enum Mode
Insert
Update
Both
End Enum
Private _IsMandatory As Boolean
Private _NotAllowed As String
Private _Message As String
Private _Mode As Mode
' Constructor
Public Sub New(ByVal ismandatory As Boolean, ByVal notallowed As String, ByVal message As String, ByVal mode As Mode)
Me._IsMandatory = ismandatory
Me._NotAllowed = notallowed
Me._Message = message
_Mode = mode
End Sub
Public ReadOnly Property IsMandatory() As Boolean
Get
Return _IsMandatory
End Get
End Property
Public ReadOnly Property NotAllowed() As String
Get
Return _NotAllowed
End Get
End Property
Public ReadOnly Property Message() As String
Get
Return _Message
End Get
End Property
Public ReadOnly Property ModeType() As Mode
Get
Return _Mode
End Get
End Property
End Class
Function for checking attributes:
Public Shared Function Validate(ByVal obj As Object, ByVal mode As ValidationAttribute.Mode) As Boolean
Dim t As Type = obj.GetType()
Dim isValid As Boolean = True
Dim message As New StringBuilder
message.Append("<ul>")
For Each mInfo As PropertyInfo In t.GetProperties
Dim CustAttr As ValidationAttribute
CustAttr = CType(Attribute.GetCustomAttribute(mInfo, GetType(ValidationAttribute)), ValidationAttribute)
'validate is mode are same, else ignore it
If mode = CustAttr.ModeType Or CustAttr.ModeType = ValidationAttribute.Mode.Both Then
'if user have defined property as mandatory
If CustAttr.IsMandatory Then
If mInfo.GetValue(obj, Nothing) Is Nothing Then
mInfo.SetValue(obj, CustAttr.NotAllowed, Nothing)
End If
If CustAttr.NotAllowed = mInfo.GetValue(obj, Nothing).ToString() Then
message.Append("<li>" + CustAttr.Message + "</li>")
isValid = False
End If
End If
End If
Next
message.Append("</ul>")
If Not isValid Then
Throw New ArgumentNullException("<br/><b>Please check below message for error details:</b> <br/><br/>" + message.ToString())
End If
Return True
End Function
Where first parameter will be object of the class on which attributes are defined.