Hello I am facing a small design problem with my application (.NET Core 2.2 API).
I want to create a custom ValidationAttribute that would be able to check if a certain property matches a Regex pattern.
What differs this attribute from built-in RegularExpressionAttribute is that patterns will be stored in the DB lookup table in format [column_name|regex_patter].
For simplicity, let's say that a class that is used to load this lookup table is called IDataRepository and a method that returns that dictionary is called LoadRegexPatterns()
I would like to be able to use the attribute like:
[RegexPattern("human_name")]
public string FirstName {get;set;}
[RegexPattern("human_name")]
public string LastName {get;set;}
I am not sure which place would be the best to load the lookoup dictionary and how to handle passing it, in the way custom ValidationAttribute could use it. I would appreciate any tips.
I can't use
IDataRepositoryinside an attribute class, because I would have to inject it there.Maybe a "singleton lookup dictionary" with values from the BD? But still - how to handle it inside the
Startupclass so it could be used byValidationAttribute
public sealed class RegexPatternAttribute : ValidationAttribute { private readonly string _columnName;
public RegexPatternAttribute(string columnName)
{
_columnName = columnName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// var regexPattern = LOAD REGEX PATTERN SHOULD BE LOADED HERE FROM SOME KIND OF LOOKUP TABLE
string inputValue = value.ToString();
if (Regex.IsMatch(inputValue,regexPattern))
{
return ValidationResult.Success;
}
else
{
return new ValidationResult(ErrorMessage);
}
}
}
IDataRepositoryinterface and pass it to the custom validation attribute. Check the following post: Passing parameter to a custom validation attribute in asp.net mvc