I have an input where it is filled with hours (####: ##), for example: 1250: 00, 0800: 00, ... I need to know if it was spelled correctly and not 1250: 66, 0800: 99 There is a mask that does not allow typing letters or spaces
I have an input where it is filled with hours (####: ##), for example: 1250: 00, 0800: 00, ... I need to know if it was spelled correctly and not 1250: 66, 0800: 99 There is a mask that does not allow typing letters or spaces
Use the onblur
event in the input so just use split
to divide both numbers, so 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've used regex to facilitate, it works more or less like this
^(\d{2}|[1-9]\d+)$
^
fetches 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 signal is called pipe) in the regex we check if the numbers are greater than 09, then with [1-9]
we check if the expression starts with 1 to 9 to be a valid value \d+
the plus sign says the expression that should search for numbers continuously until it finds another expression, that is, it can have one or more numbers followed )
ends the group, and thus ends both conditions $
"determines" that the expression should terminate right there, and can not contain anything else after the number I would like to do without regex, but I would get the code a bit bigger.
You can also try to solve everything with regex, as long as it does not 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">
Now I only have regex, without split
, what I did was add :[0-5]\d
, explaining:
:
is only to check the divider between hour and minutes [0-5]
check if the first digit of the minutes is no more than 5, that is if typing something like 10:61
will clear the field \d
at the end it looks for a number, it's equivalent to typing [0-9]