I am currently using the EmailAddressAttribute validation class on a string property in my view model. The problem I am running into is that on the client-side, jQuery validation allows for emails in the following format, "someDude@test" however when the view model is submitted, the ModelState fails because EmailAddressAttribute does not accept addresses in that format.
The only workaround I can think of is either applying a regex on the server side or create a custom jQuery validation rule.
Is there a cleaner fix to this?
So I ended up taking jwats1980 advice and creating a new custom validation attribute that agrees with the jQuery validation. Below is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Net.Mail;
using System.Web.Mvc;
namespace SWCGPExternal.Attributes
{
public class CustomEmailAddressAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
if (value == null)
return false;
try
{
MailAddress m = new MailAddress((string)value);
return true;
}
catch (FormatException)
{
return false;
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = this.ErrorMessage,
ValidationType = "email"
};
return new[] { clientValidationRule };
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.