-1

I want a textbox to have a value between 0 and 24. However the below pattern does not seem to be working.

Regex regex = new Regex("^([0-9]|1[0-9]|2[0-4])$");
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
simmy
  • 19
  • 5
  • 2
    A regex is the wrong tool for this job. If you're in WPF you can use the [Range] attribute as a validator. – PhonicUK Jun 26 '19 at 15:55
  • The pattern itself seems to work. https://regex101.com/r/G2u8Yq/1 Perhaps [this page](https://stackoverflow.com/questions/1734511/how-can-i-set-regular-expression-on-textbox) can be helpful. – The fourth bird Jun 26 '19 at 16:03
  • Making the Range attribute play nicely with WPF [requires a bit more work](https://stackoverflow.com/questions/29939996/having-range-attribute-and-one-extra-number/29940586#comment48001779_29939996). And note that [the documentation for RangeAttribute](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.rangeattribute?view=netframework-4.8) demonstrates its use with fields, but in WPF you must use a property for Bindings to work. – 15ee8f99-57ff-4f92-890c-b56153 Jun 26 '19 at 16:12
  • What are you actually doing with that regex? Please provide [a minimal working example](https://acronyms.thefreedictionary.com/MVCE) of your validation scheme, XAML and C#, for one property using that regex, and explain exactly what is "not working". – 15ee8f99-57ff-4f92-890c-b56153 Jun 26 '19 at 16:13
  • Can't you just cast it to an `int` or `double` or whatever you need and then check if it's between 0 and 24? Feels like that would make your intentions way clearer – IDarkCoder Jun 28 '19 at 08:21
  • 1
    Yup. Exactly what I did later @IDarkCoder – simmy Jul 01 '19 at 20:41

1 Answers1

0

I'm not sure what WPF is, but this expression might likely validate 0-24:

^[0-9]$|^[1][0-9]$|^[2][0-4]$

In this demo, the expression is explained, if you might be interested.

Emma
  • 27,428
  • 11
  • 44
  • 69