Search code examples
asp.netasp.net-mvcentity-frameworkwebformsscaffolding

Datatype validation is not working in web form scaffolding


I am using the Web Forms Scaffolding tool using visual studio for web forms. Everything works great so far except the Datatype email and phone number validation does work as expected. There is data validation checks when you add:

 [DataType(DataType.PhoneNumber, ErrorMessage = "Phone number is not valid")]
 public string TitleEmail { get; set; }

 [DataType(DataType.EmailAddress, ErrorMessage = "Email address is not valid")]

Without overriding the validation, I had to use a regular expression.

[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Email was invalid.")]
[RegularExpression(@"^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$", ErrorMessage = "Invalid phone number format.")]

Does anyone know why the default validation isn't working for Web Forms Scaffolding or get it to work again?


Solution

  • Adding as an answer...

    You can use the [EmailAddress] attribute to validate an email address. in .NET 4.5. The [DataType(DataType.EmailAddress)] is only for display purposes (using DisplayFor will cause it to render a mailto link instead of plain text).