The code below for date comparison works for condition if >=
and else.
function validaDatas(){
var dataInicial = new Date($("input[name='datainicial']").val());
var dataFinal = new Date($("input[name='datafinal']").val());
if (!dataInicial || !dataFinal) return false;
if (dataInicial >= dataFinal) {
alert("dataInicial maior que DataFinal ou datas iguais");
}else{
alert("dataInicial menor que DataFinal");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formaction="javascript:void(0)" onsubmit="return validaDatas()">
<div>
<label>Data inicial:</label>
<input type="date" name="datainicial" />
<label>Data Final:</label>
<input type="date" name="datafinal" />
</div>
<button>Enviar</button>
</form>
But if you put a else if
separating the condition of equal dates ==
the script does not work in this condition
function validaDatas(){
var dataInicial = new Date($("input[name='datainicial']").val());
var dataFinal = new Date($("input[name='datafinal']").val());
if (!dataInicial || !dataFinal) return false;
if (dataInicial > dataFinal) {
alert("dataInicial maior que DataFinal");
}else if (dataInicial == dataFinal){
alert("dataInicial igual a DataFinal");
}else{
alert("dataInicial menor que DataFinal");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formaction="javascript:void(0)" onsubmit="return validaDatas()">
<div>
<label>Data inicial:</label>
<input type="date" name="datainicial" />
<label>Data Final:</label>
<input type="date" name="datafinal" />
</div>
<button>Enviar</button>
</form>
WHY?