Knowing if the time is right

Asked

Viewed 31 times

0

I have an input where it is filled with hours (####:##), for example: 1250:00, 0800:00, ... I need to know if it was typed correctly and not 1250:66, 0800:99 There is a mask that does not allow typing letters or spaces

1 answer

2


Use the event onblur in the input then just use split to split both numbers, this way the event will validate the values and clear the input if they are incorrect, for example:

var hora = document.getElementById("hora");

hora.addEventListener('blur', function () {
     var valores = this.value.split(':');

     if (!valores[0] || !valores[1]) return;

     var hora = valores[0];
     var minutos = valores[1];

     if (!/^(\d{2}|[1-9]\d+)$/.test(hora) || minutos > 59) {
         this.value = ''; //Apaga os valores do campo
     }
});
<input id="hora" value="10:00">

Of course, for the hours I used to facilitate, it works more or less like this

 ^(\d{2}|[1-9]\d+)$
  • ^ seeks expression from the beginning
  • ( starts a group, because we have two conditions for the hour, with two digits, which can be hours like 00, 01, 02, 03, 04, 05, 06, 07, 08 and 09
  • \d{2} checks if it has 2 digits, referring to the numbers above
  • | after the "pipe" (the | sign is called pipe) in the regex we check if the numbers are greater than 09, then with the [1-9] we checked if the expression starts with 1 up to 9 to be a valid value
  • \d+ the plus sign says the expression that must search numbers continuously until it finds another expression, that is to say it may have one or more numbers in a row
  • ) ends the group, and thus ends both conditions
  • $ "determines" that the expression must end right there, and cannot contain anything else after the number

You could do without regex, but it would get a little bigger the code.


You can also try to solve everything with regex, as long as it doesn’t get too complex to understand later, it would look something like:

var hora = document.getElementById("hora");

hora.addEventListener('blur', function () {
     if (!/^(\d{2}|[1-9]\d+):[0-5]\d$/.test(this.value)) {
         this.value = ''; //Apaga os valores do campo
     }
});
<input id="hora" value="10:00">

See that now only has the regex, without split, what I did was add :[0-5]\d, explaining:

  • : is only to check the divider between the hour and minutes
  • [0-5] checks if the first minute digit does not exceed 5, ie if you type something like 10:61 will clear the field
  • \d in the end search a number, is equivalent to type [0-9]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.