Problems validating longer than final start date

Asked

Viewed 905 times

1

I developed this Function to validate date range, but this with a flaw that I can not solve.

If I pass the values:

inserir a descrição da imagem aqui

It should enter the validation and not let save. But it does not happen and I do not know why.

    function ValidarDatas() {
        var dataInicial = $("#<%=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;

        }
    }

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 you put in your question, that is, the function expects to receive a date in the day/month/year format.

Follow below working code:

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>

<input type="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>

Browser other questions tagged

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