Reputation: 5
I am new to mvc development.i have email text box with validation using validationResult. We have requirement to add multiple email one by one. So we need to check whether email is in correct format.this is the code for validation:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
var Emailvaild = new Regex(@"^([a-za-z0-9_\-\.]+)@((\[[0-9]{1,3}" + @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-za-z0-9\-]+\" + @".)+))([a-za-z]{2,4}|[0-9]{1,3})(\]?)$");
foreach (VEmail em in Emails)
{
if (!Emailvaild.IsMatch(em.Email))
{
results.Add(new ValidationResult(em.Email + " is an invaild", new List<string> { string.Empty }));
}
}
return results;
}
It is working.each time email is validated and if it is not correct, it shows validation message. But each time it show the message one below another. For example if I have 20 email and each email is not in correct format. So it shows 20 message one below another. I want to join the email using comma.
Upvotes: 1
Views: 187
Reputation: 218812
Your current code is adding a new ValidationResult
object for each bad email inside the loop iteration. You can move that out of the foreach loop and add the bad emails to another collection inside the loop and use string.join
method to create string which is a comma separated list of the items in that collection (bad emails) and use that for your single ValidationResultobject.
var results = new List<ValidationResult>();
var wrongEmails = new List<string>();
foreach (VEmail em in Emails)
{
if (!Emailvaild.IsMatch(em.Email))
{
wrongEmails.Add(em.Email);
}
}
if(wrongEmails.Any())
{
results.Add(new ValidationResult("Below emails are not good!"
+ string.Join(",",wrongEmails),
new List<string> { string.Empty }));
}
return results;
Upvotes: 1