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?
To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With