35

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?

3
  • Is your property an array? It is just a string in your code snippet? Commented May 29, 2015 at 14:29
  • sorry I just just meant an array as in 1234 or hello Commented May 29, 2015 at 14:34
  • 1
    To clarify why the regex is wrong, ^ inside [] means not - so you're saying: allow anything except numbers. Commented Jul 5, 2017 at 8:41

4 Answers 4

59

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

Sign up to request clarification or add additional context in comments.

Comments

10

Or you could do the length validation in the regexp:

[Required]
[RegularExpression("^[0-9]{1,12}$", ErrorMessage = "...")]
public string Uprn { get; set; }

Here's the regex visualized:

Regular expression visualization

Debuggex Demo

1 Comment

This way you would only have one error message, separated out you can specify different error messages per condition :)
7

The RegEx should be ^[0-9]*$.

I.E.

The property should look like:

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

See working example.


I'm sure you already have jQuery referenced but make sure jQuery validate and Microsoft validate scripts are included.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>

<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>

Comments

3

I suggest you use either:

[RegularExpression("\d*", ErrorMessage = "UPRN must be numeric")]

*note that it will accept empty if you remove [Required] and [MinLength(1)]

or use the following:

[RegularExpression("\d+", ErrorMessage = "UPRN must be numeric")]

which will only accept one more digits

you can test your regular expressions here: https://regex101.com/

1 Comment

This will accept alphanumeric characters. Use "^[\d]*$ " to restrict to numeric only

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.