Check and display message if the date is less than the current date

0

I have a field in my system, where I would like to display a real-time message if the date entered is earlier than today's date. It would not be a validation, just show the alert. I am having difficulty with the condition and syntax for not having DateTime.Now. Here is the code:

<p>
<label>Último Dia:</label>
<input type="text" class="Data" name="DefinirUltimoDia" id='UltimoDiaDemissao' value=""  />
</p>

JS

var formulario = document.getElementById(fAgentes),
	    UltimoDiaDemissao = document.getElementById(UltimoDiaDemissao);

        form.onsubmit = function () {
            if (UltimoDiaDemissao.value < DateTime.Now) {
                alert("Atenção: Data do último dia anterior a data atual");
                return false;
            } 
    
asked by anonymous 19.09.2018 / 22:42

1 answer

0

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

    
19.09.2018 / 23:20