Toto
Toto

Reputation: 972

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

Upvotes: 1

Views: 655

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627335

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.

Upvotes: 1

hptruc
hptruc

Reputation: 26

In my opinion, customizing a control can be complex and may lead to various issues. Instead, you can use a time input type as follows:

<MudTextField T="string" Label="Duration" InputType="InputType.Time"/>

Upvotes: 0

Related Questions