I have to validate email through several validators. I have class(EmailValidator) that has list of validators(RegexValidator, MXValidator…) and it validates email through that validators.
RegexValidator, for example, has its own validators for each provider. If it recognizes that this is gmail, so it check if it match specific pattern, if it is mygmail, so it checks if it match mygmail’s pattern otherwize it return true.
MXValidator will validates something else.
What is the correct design pattern to implement this?
public interface IValidator
{
bool Validate(string email);
}
public class RegexValidator : IValidator
{
private const string EMAIL_REGEX = @"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b";
public bool Validate(string email)
{
var regex = new Regex(EMAIL_REGEX);
var isEmailFormat regex.IsMatch(email);
if(isEmailFormat)
{
//here it should recognize the provider and check if it match the provider's pattern
}
return true;
}
}
Chain of Responsibility.
As soon as one validator finds invalid pattern, returns false. You pass an ordered list of validators.
Assuming
UPDATE
I see this implemented as another validator: