Omar Odeh
Omar Odeh

Reputation: 43

How prevent invalid time value in jquery timepicker?

I'm using JQuery timepicker and trying to prevent the user to insert invalid characters (letters).

Knowing that I have 4 time formats in my system so I can't use RegExp or mask.

So i want to know if there is a way to do that or not.

$('.gcureservationtimepicker').timepicker({
    timeFormat: '@AdminSiteHelper.GCUTimeFormat()',
    // timeFormat: 'HH:mm:ss',
    interval: 15,
    //maxTime: '12:00 PM',
    //defaultTime: '8',
    //startTime: '10:00',
    dynamic: false,
    dropdown: true,
    scrollbar: true,
    change: GenerateNewTimePicker
});

Upvotes: 0

Views: 760

Answers (1)

Mihail Minkov
Mihail Minkov

Reputation: 2633

From what I see on Timepicker's Docs, it basically interprets what you write in the field, so disabling the use of letters would be limiting its functionality.

If you desire to limit the options to something like only picking hours I would recommend you use Pickadate as a time picker. It's similar in usage, but the field is read-only.

UPDATE

If you can't change the library and need to use timepicker what I would consider is limiting the input options of the input. Something like the example below.

Also, another option, depending on your compatibility requirements could be to use <input type="time"> which already has many of the restrictions you need in place.

Additional Note

If you like you could also work deeper into the simple validation I added below and work either with regular expressions or with positioning. Something like:

  1. Characters 1 and 2 can only be numbers from 00 to 23 or from 01 to 12, depending if it's 12h or 24h.
  2. Character 3 can only be a colon.
  3. Characters 4 and 5 can only be numbers.
  4. Input string can have a maximum of 5 characters.

A regular expression for the above structure (without validation of minimum and maximum numbers) could be: ^\d{2}:\d{2}$.

function checkNumber() {
  var e = event || window.event; // get event object
  var key = e.keyCode || e.which; // get key cross-browser

  var allowedKeys = [8, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 186]; // includes backspace, numbers and :

  if (!allowedKeys.includes(key)) {
    if (e.preventDefault) e.preventDefault(); //normal browsers
    e.returnValue = false; //IE
  }
}
<input type="text" id="onlytime" onkeydown="checkNumber()" placeholder="Input time">

<br><br>

<input type="time" id="justintime">

Upvotes: 1

Related Questions