JohnAtrik
JohnAtrik

Reputation: 175

How to only allow valid dates in a Kendo MaskedTextBox

I have a Kendo MaskedTextBox that is shown below.

@(Html.Kendo().MaskedTextBox()
    .Name("kendoMaskedTextBox1")
    .Rules(rules =>
    {
        rules.Add('0', "/[0]{1}[1]{1}/");
    })
    .Mask("00/00/0000")
)

My question is how can I add rules so that it has the format of: MM/DD/YYYY but at the same time does not allow 00. Basically, for the MM/DD part I want it to see if for MM if the first value is 0 if so the next value can only be 1-9 for DD if the first value is 0 the next value can only be 1-9, etc. but for YYYY I want to allow 000 but not 0000.

Can someone help me get started with this, maybe just the MM part so I can try the others myself?

Here is what I need in more clear terms:

MM should only be values of either: 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12

Upvotes: 1

Views: 4341

Answers (2)

Jim
Jim

Reputation: 1

I'm pretty sure in the MaskedTextBox, the RegEx in a rule must be an allowable set for a single character. in your case, you're trying to make "0" in the mask represent two characters /0[1-9]|1[0-2]/, which it can't do. You could make separate rules for each digit, but that would still allow 00 and 19 for months.

I tried setting a rule for a two-character code "JJ", but that didn't work either. I also tried using both a MaskedTextBox and a DatePicker together on the same input with less than stellar results.

You could do a set of keyup checks and make sure the pieces are correct and make "corrections". I find that sort of UI frustrating though, and it would likely be a bunch of work to make sure you catch or allow all the possible permutations.

I think tenub has it right, your best bet using either control will be to use a set of validation (either on blur or prior to consuming the value) that ensures that the data in the field is a proper date.

Upvotes: 0

tenub
tenub

Reputation: 3446

Break it down piece by piece. Start with the easiest restriction first, the month:

0[1-9]|1[0-2]

Then move on to the day:

0[1-9]|[12][0-9]|3[01]

And then the year:

(?!.*0000$)\d{4}

And finally combine it all into one RegEx:

^(?:0[1-9]|1[0-2])(?:0[1-9]|[12][0-9]|3[01])(?:(?!.*0000$)\d{4})$

Do note that invalid dates could still be entered, such as 02/31/2002, and that the only method to truly validate a date is to programmatically create a Date object from the input string and test if it parses correctly.

Upvotes: 2

Related Questions