Evening all!
I've created the below validation attribute to check a list of emails are valid.
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class EmailAddressListAttribute : ValidationAttribute, IClientValidatable
{
private const string RegexPattern = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*" +
@"@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ErrorMessage = $"{validationContext.DisplayName} contains invalid email addresses";
var emailList = value.ToString().Split(';');
return emailList.Where(e => !IsValidEmail(e))
.ToList()
.Count == 0 ? null : new ValidationResult(ErrorMessage);
}
private static bool IsValidEmail(string emailAddress)
{
return Regex.IsMatch(emailAddress, RegexPattern, RegexOptions.IgnoreCase);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "emailaddresslist"
};
}
}
I want to be able to utilize this on the client side but I'm unsure how I go about doing this. Any suggestions would be greatly appreciated.
Cheers,
Z
EDIT
I've added the below JS code as a file and I'm rendering it on my view. It's running on page load but doesn't seem to do anything when submit the form.
(function ($) {
$.validator.unobtrusive.adapters.addSingleVal("emailaddresslist");
$.validator.addMethod("emailaddresslist", function (value, element, params) {
return false;
});
}(jQuery));