Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Validation make RegularExpression numeric only on string field

Tags:

c#

asp.net-mvc

I have the following property in my view model:

[Required] [MaxLength(12)] [MinLength(1)] [RegularExpression("[^0-9]", ErrorMessage = "UPRN must be numeric")] public string Uprn { get; set; }     

Regardless of Uprn being a string, I want to throw a validation error if there is anything other than numbers entered into the Uprn box on page submit.

With the above, I am getting the error "UPRN must be numeric" whether its a string or int

What's going on here?

like image 652
JsonStatham Avatar asked May 29 '15 14:05

JsonStatham


People also ask

What is the regular expression for numbers only?

To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers.

What is an attribute in data annotation?

We'll use the following Data Annotation attributes: Required – Indicates that the property is a required field. DisplayName – Defines the text to use on form fields and validation messages. StringLength – Defines a maximum length for a string field. Range – Gives a maximum and minimum value for a numeric field.

What is MVC regex?

The Spring MVC Validation allows us to validate the user input in a particular sequence (i.e., regular expression). The @Pattern annotation is used to achieve regular expression validation. Here, we can provide the required regular expression to regexp attribute and pass it with the annotation.

What are data annotations in MVC?

In ASP.NET MVC, Data Annotation is used for data validation for developing web-based applications. We can quickly apply validation with the help of data annotation attribute classes over model classes.


1 Answers

The regular expression is wrong. Replace it with:

[Required] [MaxLength(12)] [MinLength(1)] [RegularExpression("^[0-9]*$", ErrorMessage = "UPRN must be numeric")] public string Uprn { get; set; }     

Don't forget to include:

@Scripts.Render("~/bundles/jqueryval") 

in your view for the jquery validation

like image 103
Jimmyt1988 Avatar answered Sep 20 '22 15:09

Jimmyt1988