Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mvc validation regular expression only numbers?

I tried the following code for digits-only validation for a contact number validation in Mvc web app.

[RegularExpression(@"/(^\(\d{10})?)$/", ErrorMessage = "Please enter proper contact details.")]
[Required]
[Display(Name = "Contact No")]
public string ContactNo { get; set; }

But the validation expression is not working.

For the contact number I want to only accept digits. It can be either a 10 digit mobile number or a land-line number.

like image 315
Neo Avatar asked Jan 12 '12 17:01

Neo


2 Answers

If don't have any restrictions other than numbers only, this should fit:

[RegularExpression(@"^\d+$", ErrorMessage = "Please enter proper contact details.")]
[Required]
[Display(Name = "Contact No")]
public string ContactNo { get; set; }
like image 50
gdoron is supporting Monica Avatar answered Oct 03 '22 01:10

gdoron is supporting Monica


/ / is javascript way to build a regular expression literal object. In .NET you should not use it.

Try the following:

@"^\((\d{10}?)\)$"

or if you want exactly 10 digits:

@"^(\d{10})$"
like image 29
Darin Dimitrov Avatar answered Oct 03 '22 00:10

Darin Dimitrov