Search code examples
c#regexvalidationblazormudblazor

Regex mask for MudTextField for minutes and seconds validation


I have a text field for the user to pick a minutes+seconds time duration. I am trying to use a IMask object for restricting the input using a regex.

The problem is that this completely blocks the input, and I can not even begin to type a single digit, which I don't understand because as you can see on those links the two regex that I use work properly :

^[0-5]?\d:[0-5]\d$ https://regex101.com/r/ZKO3oE/1

^([0-5]?[0-9]):([0-5]?[0-9])$ https://regex101.com/r/aM7NHi/1

My code looks like this and you can try it on the link below:

<MudTextField Mask="@mask1" Label="Duration"  HelperText="@mask1.Mask"
                  @bind-Value="minutesAndSec"  Variant="@Variant.Text" Clearable />

IMask mask1 = new RegexMask(@"^[0-5]?\d:[0-5]\d$");

You can try my code here:

https://try.mudblazor.com/snippet/wOQnbvPhASvzgOyF

I must be missing something? Any input is greatly appreciated, thanks a lot


Solution

  • You need to make sure your input (even incomplete) fully matches the pattern.

    That means that both your patterns must look like

    @"^[0-5]?(?:\d(?::(?:[0-5]?\d)?)?)?$"
    

    Use the same pattern for both time and duration.

    Details:

    • ^ - start of string
    • [0-5]? - an optional digit from 0 to 5
    • (?:\d(?::(?:[0-5]?\d)?)?)? - an optional sequence of
      • \d(?::(?:[0-5]?\d)?)? - a digit and then an optional sequence of
        • :(?:[0-5]?\d)? - a : char and then an optional sequence of
          • [0-5]?\d - an optional 0 to 5 digit and then any single digit
    • $ - end of string.