comparison of dates with javascript

Asked

Viewed 61 times

0

I got two camps like date in my form, the field data_inicio and data_fim.

I need to ride a script that when I finish filling out the dates, that is when the fields lose focus, an alert is issued warning if data_inicio is larger than the data_fim, whereas the data_inicio never may be greater than the data_fim.

I already made a script using the event onclik, but it only warns when I click on submit.

Follow the code below:

 function comparadatas()
 {
   var data_inicio = document.getElementById("data_inicio").value;
   var data_fim = document.getElementById("data_fim").value;
    
    if(data_inicio > data_fim){
        alert("ERRO! A DATA DE NOTICAÇÃO NAO PODE SER MAIOR DO QUE A DATA DE COMPARECIMENTO");   
    }
 }
<form>
  <label for="data_inicio">Data Inicio</label>
  <input type="date" name="data_inicio" id="data_inicio"><br/>

  <label for="data_fim">Data Final</label>
  <input type="date" name="data_fim" id="data_fim"><br/>

  <input type="submit" value="REALIZAR CADASTRO" onclick="comparadatas()">
</form>

2 answers

0

Just use the event onblur. This event will be sent when a particular element loses focus.

You can pass the attribute onblur="comparadatas" date elements or use Js to define. I used js in the example below for the sake of taste.

const data_inicio = document.getElementById("data_inicio");
const data_fim = document.getElementById("data_fim");

data_inicio.addEventListener("blur", () => {
  comparadatas();
});

data_fim.addEventListener("blur", () => {
  comparadatas();
});

function comparadatas() {
  if (data_inicio.value == "" || data_fim.value == "") return false;
  
  if (data_inicio.value > data_fim.value) {
    alert("ERRO! A DATA DE NOTICAÇÃO NAO PODE SER MAIOR DO QUE A DATA DE COMPARECIMENTO");
  }
}
<form>
  <label for="data_inicio">Data Inicio</label>
  <input type="date" name="data_inicio" id="data_inicio"><br/>

  <label for="data_fim">Data Final</label>
  <input type="date" name="data_fim" id="data_fim"><br/>

  <input type="submit" value="REALIZAR CADASTRO" onclick="comparadatas()">
</form>

0

<script>
function comparadatas() {
  const data_inicio = document.getElementById("data_inicio");
  const data_fim = document.getElementById("data_fim");
  if (data_inicio.value == "" || data_fim.value == "") return false;

  if (data_inicio.value > data_fim.value) {
    alert("A DATA DE NOTICAÇÃO NAO PODE SER MAIOR DO QUE A DATA DE COMPARECIMENTO!");
  }
}
</script>

<form>
  <label for="data_inicio">Data Inicio</label>
  <input type="date" name="data_inicio" id="data_inicio"><br/>

  <label for="data_fim">Data Final</label>
  <input type="date" name="data_fim" id="data_fim" onblur="comparadatas()"><br/>

</form>
  • Good morning guys, thank you so much for your help, I managed to solve

  • Missed to mark the other as correct. '-'

Browser other questions tagged

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