Problems to validate starting date greater than final

1

I have developed this function to validate date range, but it has a flaw that I can not resolve.

If I pass the values:

Youshouldentervalidationanddonotletsave.ButitdoesnothappenandIdonotknowwhy.

functionValidarDatas(){vardataInicial=$("#<%=txtDtIni.ClientID%>").val();
        var dataFinal = $("#<%=txtDtFim.ClientID%>").val();
        if (dataInicial > dataFinal) {
            criarDivAlert("Alerta", "Intervalo de datas inválidos");
            exibirAlerta(false);
            $("#<%=txtDtFim.ClientID%>").focus();
            cancelPostback = true;

        }
    }
    
asked by anonymous 02.01.2018 / 14:17

1 answer

1

You are comparing texts and not dates, so the comparison does not return the expected result.

I created a function to convert the text to date based on the image that you put in your question, that is, the function expects to receive a date in the day / month / year format.

Below is code working:

function ValidarDatas() {
    var data1 = $("#data1").val();
    var data2 = $("#data2").val();
    
    var dataInicial = ConverteParaData(data1);
    var dataFinal   = ConverteParaData(data2);
    
    
    if (dataInicial > dataFinal) {
        console.log("Data inválida!");
    }else{
        console.log("Data válida!");
    }
}

function ConverteParaData(data){
  var dataArray = data.split('/');
  var novaData = new Date(dataArray[2], dataArray[1], dataArray[0]);
  
  return novaData;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="data1" name="data1" value="31/12/2017" />
<input type="text" id="data2" name="data2" value="02/01/2018" />

<button type="button" id="validar" onclick="ValidarDatas()">
  Validar
</button>
    
02.01.2018 / 14:44