At first, I noticed that you referred to the form with the variable formulario
, but used onsubmit
in a form
variable. I do not know if it was a mistake or purpose, but anyway.
To get the current date, just create a date object with no parameters. Already the date entered by the user will come as a string, not a date, so it needs to be parsed.
So I understand, you want to see in real time, before the person sends the form, so in case you should use the onfocusout
event, the onsubmit
event will only trigger when the form is sent.
See:
var input = document.getElementById('UltimoDiaDemissao'),
hoje = new Date().setHours(-1),
ultimoDiaDemissao;
input.onblur = function () {
ultimoDiaDemissao = new Date(input.value.split('/').reverse().join('-')).setHours(24);
if (ultimoDiaDemissao < hoje) {
alert("Atenção: Data do último dia anterior a data atual");
}
}
Okay, now let's get the explanation. new Date()
returns the current date in a date object. All that code for UltimoDiaDemissao
works like this:
To pass the date to the object Date
, you need to send a string in yyyy-mm-dd
format, and your string comes in the Brazilian format. Then .split('/')
will split the day, month and year into 3 parts in an array, reverse()
will invert the order of the array, putting the year ahead and the day at the end, and then putting everything together in a string with join('-')
separated with dash instead of slash. Only then in the end will setHours(24)
fix a problem with UTC time zone, if you need detail on it take a look at the Date
object of javascript #.
This has two date objects to compare correctly, and the rest is only activated whenever the person takes focus from the date input.
Functional JsFiddle