How to validate KendoTimePicker with mask but still allow no date

1 Answer 364 Views
Date/Time Pickers DateInput
Lee
Top achievements
Rank 2
Bronze
Bronze
Bronze
Lee asked on 26 Jul 2021, 05:51 PM | edited on 26 Jul 2021, 07:24 PM

I have two Kendo Time Pickers on my page. Both are optional but I want to prompt the user to input the value in the format hh:mm am/pm. I want to use the KendoValidator to validate that the values are either empty or contain a valid time. Also, for the second input (end time), a valid time must exist in start time and it cannot come before the start time.

The first issue I am running into is that when using the dateInput: true option to enforce the format it is sending the string "hh:mm am/pm" to the validator as the date when the user enters nothing. Since this is not null it tries to validate it which it of course fails since "hh:mm am/pm" is not a date. This is also causing an issue with validating the required attribute on the startDate. 

Another issue would be that this gets passed to the server as the invalid date string which would potentially cause issues on the back end.

Finally, when I do not enter a start date at all it should trigger the required message but it is not. 

How can I solve this issue? Here is what my code looks like at the moment:

 

Initialize Time Pickers:

$.each($(".js-time-picker"), function (index, picker) {
    let id = $(picker).attr("id");
    timePickers[id] = $(`#${id}`).kendoTimePicker({
        dateInput: true,
        format: "h:mm tt",
        parseFormats: "HH:mm",
    }).data("kendoTimePicker");
    timePickers[id]._dateInput.setOptions({
        messages: {
            hour: "hh",
            minute: "mm",
            dayperiod: "am/pm"
        }
    });
});

Validator: 


$(document).ready(function () {
    myValidator = $("#myForm").kendoValidator({
        rules: {
            timeValidation: function (input) {
                if ($(input).hasClass("js-time-picker")) {
                    var validDate = kendo.parseDate($(input).val());
                    if (!validDate) {
                        return false;
                    }
                }
                return true;
            }

        },
        messages: {
            required: "Required",
            timeValidation: "Invalid Time"
        },
        validateOnBlur: false
    }).data("kendoValidator");
});

HTML:

            <div class="form-element">
                <label id="startTimeLabel" for="startTime">Start Time</label>
                <input id="startTime" name="startTime" class="js-time-picker" required validationMessage="Invalid time entered" aria-labelledby="startTimeLabel" />
                <span class="k-invalid-msg" data-for="startTime"></span>
            </div>

            <div class="form-element">
                <label id="endTimeLabel" for="endTime">End Time</label>
                <input id="endTime" name="endTime" class="js-time-picker" validationMessage="Invalid time entered" aria-labelledby="endTimeLabel" />
                <span class="k-invalid-msg" data-for="endTime"></span>
            </div>
There is a submit button with an onClick event that calls myValidator.validate();

1 Answer, 1 is accepted

Sort by
-1
Nikolay
Telerik team
answered on 29 Jul 2021, 02:50 PM

Hi Lee,

Here is the correct way of setting the validation rule;

        $("#form").kendoValidator({
          rules: {
            // Implement your custom date validation.
            dateValidation: function (input, params) {
              if (input.is("[title='timepicker']") && input.val() != "") {
                input.attr("data-datevalidation-msg", "Not a valid time!");

                var date = kendo.parseDate(input.val(), "HH:mm tt");
                if (date) {
                  return true;
                }
                return false;
              }
              return true;                    
            }
          },
          messages: { //custom rules messages
            datevalidation: function (input) {
              // Return the message text.
              return input.attr("data-val-datevalidation");
            }
          }
        });

You can use the custom formatting from here:

For your reference I am posting the Dojo demo I prepared demonstrating the above:

Let me know if you have any questions.

Regards,
Nikolay
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Lee
Top achievements
Rank 2
Bronze
Bronze
Bronze
commented on 15 Nov 2021, 06:28 PM

This doesn't work when the time is optional (not required) as in the end time field. Using your dojo above, delete the hours and minutes and tab out of the field. It will show "not a valid time!"  
Nikolay
Telerik team
commented on 18 Nov 2021, 01:31 PM

Hi Lee,

The validation rule you are going to write is entirely up to you. The validation rule from the Dojo I shared previously returns false if there is no time in the TimePicker. You can also adjust the validation messages as demonstrated in the following example:

I hope this clarifies the situation.

Tags
Date/Time Pickers DateInput
Asked by
Lee
Top achievements
Rank 2
Bronze
Bronze
Bronze
Answers by
Nikolay
Telerik team
Share this question
or