Validate dates with JavaScript

0

I have a problem when validating dates using JavaScript. I have the following form:

<tr> 
    <td> 
        <input type="date" name="fecha1" value="<?php echo date($fecha1);?>"> 
    </td> 
</tr> 

<tr> 
    <td> 
        <input type="date" name="fecha2" value="<?php echo date($fecha2);?>"> 
    </td> 
</tr>

<tr>     
    <td> 
        <input type="date" name="fecha3" value="<?php echo date($fecha3);?>"> 
    </td> 
</tr> 

<tr> 
    <td> 
        <input type="date" name="fecha4" value="<?php echo date($fecha4);?>"> 
    </td> 
</tr>

Where I place 4 dates.

If the database has said date, the sample, but nothing shows.

My question is: When filling out the form with the dates, how can I validate that no dates are placed before the ones already loaded, that is, for example:

Si fecha1 = x fecha 
fecha2 no debe ser menor a fecha1 
fecha3 no debe ser menor a fecha2 
fecha4 no debe ser menor a fecha3 

Is it possible?

    
asked by Pepemujica 16.01.2017 в 19:07
source

4 answers

1

It can be done by iterating the previous fields to the one that is currently being edited and checking the dates.

Note: Please note that in this code I assume that the format is ISO 8601 (yyyy-mm-dd).

let inputs = document.querySelectorAll('.input');

[].forEach.call(inputs, (input, i) => {
  input.addEventListener('input', () => {
    if (i > 0) {
      let curDate = new Date(input.value);
      [].forEach.call(inputs, (input2, k) => {
        if (k < i) { // solo recorremos inputs anteriores al actual
          let previousDate = new Date(input2.value);
          if (curDate.getTime() < previousDate.getTime()) {
            input.classList.add('invalid');
          } else {
            input.classList.remove('invalid');
          }
        }
      });
    }
  });
});
*, *:before, *:after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
.input {
  border: 1px solid #ddd;
  border-radius: 3px;
  box-shadow: 0 1px 4px 0 rgba(0,0,0,.075) inset;
  padding: .5rem .85rem;
  width: 0;
}
.input.invalid {
  border-color: #d53400;
}
.input:focus {
  outline: none;
}
form {
  margin: 20px auto;
  width: 400px;
}
form article {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
form article .input { 
  flex-basis: 45%;
  margin: 5px 0;
}
form footer {
  padding: .5rem 0;
  text-align: right;
}
.btn {
  background-color: #f2f2f2;
  border: 1px solid transparent;
  border-radius: 3px;
  color: #555;
  padding: .5rem 1rem;
}
.btn.success {
  background-color: #2ecc71;
  color: #fff;
}
<form id="datesForm">
  <article>
    <input type="text" class="input" size="5" />
    <input type="text" class="input" size="5" />
    <input type="text" class="input" size="5" />
    <input type="text" class="input" size="5" />
  </article>
  <footer>
    <button class="btn success">Registrar</button>
  </footer>
</form>

In case you want to deal with another type of date format, you should identify the format and convert them to ISO 8601, which is the one that understands JavaScript. However, with Moment you can make things easier for yourself.

let curDate = moment(input.value);
...
let previousDate = moment(input2.value);

if (curDate < previousDate) {
  input.classList.add('invalid');
} else {
  input.classList.remove('invalid');
}

On the Moment documentation you can see the formats of supported dates.

    
answered by 16.01.2017 в 20:41
0

Try this.

You are supposed to validate the specific date with the previous one, the first date should go by default, the rest is compared with the previous one, I hope that is what you are looking for:

<tr> 
    <td> 
        <input type="date" name="fecha1" value="<?php echo date($fecha1);?>"> 
    </td> 
</tr> 

<tr> 
    <td> 
        <input type="date" name="fecha2" value="<?php 
            if ($fecha2 < $fecha1) {
                echo "No se agrega porque es menor";
            } else {
                echo date($fecha2);
            }
        ?>"> 
    </td> 
</tr>

<tr> 
    <td> 
        <input type="date" name="fecha3" value="<?php 
            if ($fecha3 < $fecha2) {
                echo "No se agrega porque es menor";
            } else {
                echo date($fecha3);
            }
        ?>">  
    </td> 
</tr> 

<tr> 
    <td> 
        <input type="date" name="fecha4" value="<?php 
            if ($fecha4 < $fecha3) {
                echo "No se agrega porque es menor";
            } else {
                echo date($fecha4);
            }
        ?>"> 
    </td> 
</tr>
    
answered by 16.01.2017 в 19:42
0

Change in the code to be displayed graphically

<script type="text/javascript">

    //console.log(document.getElementsByName("fecha1"));

    function cambio (input) {

        var inputs = document.getElementsByTagName("input");

        console.log(input.value);

        var inputInt;

        for (var i = 0; i < inputs.length; i++) {

            if (inputs[i] == input) {

                inputInt = i;

            }

        }

        if (inputInt > 0) {

            if (inputs[inputInt -1].value > input.value) {

                input.style.background= "red";

            } else {

                input.style.background= "green";

            }

        } else {

            input.style.background= "green";

        }

    }

</script>

All input should go this way.

<table>

    <tr> 
        <td> 
            <input type="date" name="fecha1" value="2000-05-05" onkeyup="cambio(this)" onclick="cambio(this)">
        </td> 
    </tr> 

    <tr> 
        <td> 
            <input type="date" name="fecha2" value="2000-05-05" onkeyup="cambio(this) onclick="cambio(this)">
       </td> 
    </tr>

    <tr>
        <td> 
            <input type="date" name="fecha3" value="2000-05-05" onkeyup="cambio(this) onclick="cambio(this)">
        </td> 
    </tr> 

    <tr> 
        <td> 
            <input type="date" name="fecha4" value="2000-05-05" onkeyup="cambio(this) onclick="cambio(this)">
        </td> 
    </tr>

</table>

Once you see that it worked, change the values of input for yours.

  

Note: If you have more input you would have to do a validation to only take those 4, since in the function JavaScript reviews all inputs .

    
answered by 16.01.2017 в 20:34
0

You could try a "change" event, when changing the value typed in the input, something like

$("#fecha1, #fecha2, #fecha3, #fecha4").on('change', function(){ if(#fecha1 && #fecha1 >= #fecha2){//Y acá haces la alerta o el código que se debe ejecutar al cumplir la condición..} })

This validates if there is a date1, and if the date1 is greater or equal to the date2, and so on with the other dates

Or if you wish, you can validate it when you submit it in the "submit", all dates, ex:

$("#form").on('submit', function (event) { event.preventDefault(); if ($("#fecha1").val() && $("#fecha1").val() >= $("#fecha2").val()) { alert("La fecha1 es mayor o igual que la fecha2") } })

And you repeat the same condition with the rest of the dates

    
answered by 12.01.2019 в 20:11