在ASP.NET MVC上的.NET 4.8中,电子邮件验证需要进行更改。以下是一种
首先,打开EmailAttribute.cs文件。
在Validate方法中,添加以下代码:
if (value != null) { var email = value.ToString(); var emailRegex = new Regex(@"^[\w-.]+@([\w-]+.)+[\w-]{2,6}$"); if (!emailRegex.IsMatch(email)) { return new ValidationResult(ErrorMessage); } }
[Required] [EmailAddress] public string Email { get; set; }
[HttpPost] public ActionResult ContactForm(ContactFormModel model) { if (ModelState.IsValid) { // perform some action return View("Success"); } else { return View(model); } }
这样,电子邮件验证应该就可以正常工作了。