Lots of other questions give answers for regex expressions which only allow fully completed times like this: ^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$
But this is no use in a Textbox.TextChanged
event because while typing 15:45
the textbox will contain 15:
which doesn't match the expression above.
Is there an easy way to allow a partial match of a Regex expression to ensure a half typed time still passes or would I have to break the expression down into its parts all separated out by or
s, like this?
You may manually adjust such patterns to allow partial matches. One thing to remember is that they are only good for live validation, not final validation. To perform final validation, you need to use a complete pattern with no optional parts (or just those obligatory optional parts).
So, the technique consists in using nested optional non-capturing groups, like (?:...(?:...)?)?
.
^(?:(?:[01]?[0-9]|2[0-3])(?::(?:[0-5][0-9]?)?)?)?$
See the regex demo
Details:
^
- start of string(?:
- start of an optional non-capturing group
(?:
- start of an optional non-capturing group
[01]?[0-9]
- an optional 0
or 1
and then any 1 digit|
- or 2[0-3]
- 2
and then a digit from 0
to 3
)
- end of an optional non-capturing group(?:
- start of an optional non-capturing group
:
- a colon(?:
- start of an optional non-capturing group
[0-5][0-9]?
- a digit from 0
to 5
and then any optional digit)?
- end of an optional non-capturing group)?
- end of an optional non-capturing group)?
- end of an optional non-capturing group$
- end of string.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With