0

This is a commonly asked question. But I am not getting the answer that I need. I had a look at MVC Validation make RegularExpression numeric only on string field (among many) for reference but I am not quite there yet.

I have an html5 input field bound to an MVC property. I want to make use of the [RegularExpression()] attribute but I am not getting the output that I need. I need my input to only take the following:

A single number between 0 and 7, or the % character

I tried the following:

[RegularExpression("^[0-7][%]")].

Where am I going wrong?

Harold_Finch
  • 682
  • 2
  • 12
  • 33
  • Any number of numbers and the `%`? (you currently allow only a single number (0-7) followed by `%` –  Feb 28 '18 at 07:01
  • The input field should only take a single value whether its a number in the range `0-7` or the `%` character – Harold_Finch Feb 28 '18 at 07:02
  • 1
    You need an OR - `^[0-7]|[%]$` –  Feb 28 '18 at 07:05
  • @StephenMuecke That worked. You can mark your comment as an answer – Harold_Finch Feb 28 '18 at 07:12
  • Answers have already been added :) - but I'll update you question to make it clear what you wanted. –  Feb 28 '18 at 07:13
  • Actually, the context free regex will look like `^(?:[0-7]|%)$` or even better, `^[0-7%]$` (see [this answer](https://stackoverflow.com/a/49023809/3832970)). However, if the pattern is only used in the HTML5 pattern attribute, the `^` and `$` might be redundant, and really, `[0-7]|%` or `[0-7]|%` will also work then. – Wiktor Stribiżew Feb 28 '18 at 07:42

1 Answers1

1

If you want to use range from 0 to 7. (Only single digit at a time) then use [0-7] and for % use [%]. To concatenate both the requirements(For or condition) use | in between two square brackets.

Your regular expression would be look like this

[RegularExpression("^[0-7]|[%]")]

^ at the starting of regular expressions, suggests that your string should starts with the number.

$ mentioned by @Stephen in comments states that your % must occurs at the end of string or expression.

Now its up to you, if you want string should be in D% format, where D is for digit and %, then use ^ in the beginning and $ at the end of regex. e.g. 5%

if this is not the case, then you can remove ^ and $ from the regex e.g %

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44