0

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.

4
  • Have you tried overriding the IsValid(Object, ValidationContext) overload instead? Commented Sep 4, 2011 at 22:04
  • Well, I want bool as return value, this overload has ValidationContext return value... Any other help?? Commented Sep 5, 2011 at 17:13
  • Are you sure you cannot use following code for validation: public override ValidationResult IsValid(object value, ValidationContext context) { var user = context.ObjectInstance as MyClass; bool result = ... // Your validation logic here return result ? ValidationResult.Success : new ValidationResult(FormatErrorMessage(context.DisplayName)); } Commented Sep 5, 2011 at 20:05
  • When I use "public override ValidationResult IsValid(object value, ValidationContext context)", context is null.... Commented Sep 5, 2011 at 22:35

1 Answer 1

1

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();

        ...
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.