Reputation:
I'm trying to validate some user contact details like so:
public class Customer
{
[Display(Name = "Your e-mail :")]
[Required(ErrorMessage = "An email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string ContactEmail { get; set; }
[Display(Name = "Your contact number :")]
[Required(ErrorMessage = "A phone number is required")]
[Phone(ErrorMessage = "Invalid Phone Number")]
public string ContactNumber { get; set; }
}
In my view the email validation works great and only allows valid email addresses. However, the phone validation doesn't work at all, it allows all kinds of letters and special characters.
The documentation states that the PhoneAttribute
class
Specifies that a data field value is a well-formed phone number using a regular expression for phone numbers
So why is this not happening?
Upvotes: 4
Views: 8943
Reputation: 674
Use following Code for Phone validation.
[Display(Name = "Your contact number :")]
[Required(ErrorMessage = "A phone number is required.")]
[DataType(DataType.PhoneNumber, ErrorMessage = "Invalid Phone Number")]
[RegularExpression(@"^([0-9]{10})$", ErrorMessage = "Invalid Phone Number.")]
public string ContactNumber { get; set; }
Upvotes: 8