How to pass parameters into a ValidationAttribute?

Viewed 5918

I have a custom ValidationAttribute, it checks if another user exists already. To so it needs access to my data access layer, an instance injected into my controller by Unity

How can I pass this (or anything for that matter) as a parameter into my custom validator?

Is this possible? i.e where I'm creating Dal, that should be a paramter

public class EmailIsUnique : ValidationAttribute
    {
        private string _errorMessage = "An account with this {0} already exists";

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            DataAccessHelper Dal = new DataAccessHelper(SharedResolver.AppSettingsHelper().DbConnectionString); //todo, this is way too slow
            bool isValid = true;
            if(value == null) {
                isValid = false;
                _errorMessage = "{0} Cannot be empty";
            } else {
                string email = value.ToString();
                if (Dal.User.FindByEmail(email) != null)
                {
                    isValid = false;
                }
            }

            if (isValid)
                return ValidationResult.Success;
            else
                return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName));
        }
    }
3 Answers
Related