Question

I have made custom attribute in my asp.net mvc2 project:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class IsUsernameValidAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return true;
        }

        var username = value.ToString();

        return UserBusiness.IsUsernameValid(username) 
// && value of OtherProperty == true;
    }
}

for the model:

public class MyClass
{
    [IsUsernameValid]
    public string UserName { get; set; }

    public bool OtherProperty { get; set; }
}

I can get value of UserName, but can I get value of OtherProperty inside custom attribute and use it in return clause and how. Thanks in advance.

Was it helpful?

Solution

The only way to do this is with a class level attribute. This is often used for validating the Password and PasswordConfirmation fields during registration.

Grab some code from there as a starting point.

[AttributeUsage(AttributeTargets.Class)]
public class MatchAttribute : ValidationAttribute
{
   public override Boolean IsValid(Object value)
   {
        Type objectType = value.GetType();

        PropertyInfo[] properties = objectType.GetProperties();

        ...
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top