Check for a string containing comma delimited emails

I am trying to verify this property in an MVC model, which can contain zero or more email addresses, separated by commas:

public class DashboardVM { public string CurrentAbuseEmails { get; set; } ... } 

The question is, how to do this using the built-in free rule for checking email addresses? Right now, I have a solution using Must and a regex that works, but I don't find it elegant enough.

  public DashboardVMValidator() { RuleFor(x => x.CurrentAbuseEmails).Must(BeValidDelimitedEmailList).WithMessage("One or more email addresses are not valid."); } private bool BeValidDelimitedEmailList(string delimitedEmails) { //... match very very long reg. expression } 

So far, the closest solution, including RuleFor (...). EmailAddress () created a custom Validator below and called a check for each letter from the line, but for some reason it didn’t work (AbuseEmailValidator was not able to get my predicate x => x - by calling validator.Validate for each letter).

 public class AbuseEmailValidator : AbstractValidator<string> { public AbuseEmailValidator() { RuleFor(x => x).EmailAddress().WithMessage("Email address is not valid"); } } 

Is there a way to do this in a simple way? Something similar to this solution, but with one line instead of a list of strings, since I cannot use SetCollectionValidator (or can I?): How do you check each row in a list using Fluent Validation?

+4
source share
1 answer

You can try something like this:

 public class InvoiceValidator : AbstractValidator<ContractInvoicingEditModel> { public InvoiceValidator() { RuleFor(m => m.EmailAddressTo) .Must(CommonValidators.CheckValidEmails).WithMessage("Some of the emails provided are not valid"); } } public static class CommonValidators { public static bool CheckValidEmails(string arg) { var list = arg.Split(';'); var isValid = true; var emailValidator = new EmailValidator(); foreach (var t in list) { isValid = emailValidator.Validate(new EmailModel { Email = t.Trim() }).IsValid; if (!isValid) break; } return isValid; } } public class EmailValidator : AbstractValidator<EmailModel> { public EmailValidator() { RuleFor(x => x.Email).EmailAddress(); } } public class EmailModel { public string Email { get; set; } } 

It seems to work fine if you use the poco middleware. My letters are separated by the letter ";" in this case. Hope this helps.

+6
source

Source: https://habr.com/ru/post/1432959/


All Articles