Date range check automatically

Asked

Viewed 62 times

0

How do I check the dates without pressing the send button? Type set an invalid date and already be alerted if it is not within range?

function checarDatas() {
    var desenhoDidatico = document.desenhoDidatico;
    console.log(desenhoDidatico);
    var data_1 = new Date(desenhoDidatico.datainicial.value);
    var data_2 = new Date(desenhoDidatico.datafinal.value);
    if (!data_1 || !data_2) return false
    if (data_1 > data_2) {
        alert("Data inserida antes do início das atividades.");
        return false;
    } else {
        return true
    }
}
<form action="" name="desenhoDidatico" onsubmit="return checarDatas()">
    <input type="date" name="datainicial" />
    <input type="date" name="datafinal" />
    <button>Enviar</button>
</form>

  • 2

    Set the validation to be executed when exiting fields (event onblur): <input type="date" name="datainicial" onblur="checarDatas()" />. See if that suits you

  • Must remove onsubmit="Return checarDatas()" from form tag?

  • 1

    No need, you can leave, because it will validate when leaving the fields with date (put the event in both) and also when submitting the form. It would only be interesting, in the case of validation when leaving the fields change a little the function, or do another, so that I can go back in the field (Focus) to make it be corrected, or even add a red border warning that it is wrong. Sure, those are just ideas, suggestions

  • Ok, it worked that way. But Alert only appears when you select another form field

  • To compare the two dates, both fields have to be selected with some date.

  • Another problem is that !data_1 and !data_2 do not guarantee that a valid date has been entered.

  • Do you use jQuery? If yes, you can make an algorithm by checking the length of both fields, to see if both fields are filled in completely, and then run the code once both fields are filled in. Puts if inside a . Trigger('change'); and the code will execute whenever a value is added or removed from inside the inputs. When both are filled in, it will perform the test function automatically, without you having to remove the focus from the fields, and can be filled in any order. That’s what you want?

  • It may be tbm...

Show 3 more comments
No answers

Browser other questions tagged

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