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));
}
}
I'm not too sure you'll be able to pass runtime parameters into your attribute.
You could use DependencyResolver.Current.GetService<DataAccessHelper>()
to resolve your dal (given that you've registered DataAccessHelper)
You're probably more likely to have registered DataAccessHelper as IDataAccessHelper or something? in which case you'd call GetService<IDataAccessHelper>
public class EmailIsUnique : ValidationAttribute
{
private string _errorMessage = "An account with this {0} already exists";
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
IDataAccessHelper Dal = DependencyResolver.Current.GetService<IDataAccessHelper>(); // 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));
}
}
or
public class EmailIsUnique : ValidationAttribute
{
[Dependency]
public IDataAccessHelper DataAccess {get;set;}
private string _errorMessage = "An account with this {0} already exists";
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
bool isValid = true;
if(value == null)
{
isValid = false;
_errorMessage = "{0} Cannot be empty";
}
else
{
string email = value.ToString();
if (DataAccess.User.FindByEmail(email) != null)
{
isValid = false;
}
}
if (isValid)
return ValidationResult.Success;
else
return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With