Well, initially, I noticed that you referenced the form with the variable formulario
, but used the onsubmit
in a variable form
. I don’t know if it was mistake or purpose, but anyway.
To get the current date, just create a date object without parameters. Already the date typed by the user will come as a string, not a date, so it needs to be parsed.
From what I understand, want to see in real time, before the person submit the form, then in case should use the event onfocusout
, the event onsubmit
will only give Trigger when the form is sent.
Behold:
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. Already all that code for the UltimoDiaDemissao
works like this:
To move the date to the object Date
, need to send a string in format yyyy-mm-dd
, and its string comes in Brazilian format. Then the .split('/')
will divide the day, month and year into 3 parts in an array, the reverse()
will invert the order of the array, putting the year in front and the day in the end, and then join everything in a string with the join('-')
separated with dash instead of slash. Only then at the end of the setHours(24)
to fix a problem with UTC time zone, if you need details about it take a look at the object Date
javascript and how it works.
Once this is done we have two date objects to be compared correctly, and the rest is just activate whenever the person takes the focus of the date input.
Functional jsfiddle
How is the date in the input? DD/MM/YYYY?
– Máttheus Spoo
Yes, DD/MM/YYYY
– Lucas Latorre