validate date is not less than today's

0

I am trying to do a validation, where the date chosen and the time is not less than today, I can not use any other framework or library more than js or jquery

<script>
	$(document).ready(function(){
    	$("#fecha").change(function(){
        	var hoy= new Date();
            var fecha=$('#fecha').val();
            var fechaFormulario=Date.parse(fecha);			
			if (hoy <= fechaFormulario) {
  				alert("Fecha a partir de hoy");
			}else {
  				alert("Fecha pasado");
			}
    	});
	});
</script>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
  <input type="datetime-local" id="fecha">
</body>
</html>
    
asked by Emmanuel 22.11.2018 в 00:11
source

1 answer

0

Your code is correct. Just put the <script> just before the </body> :

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width">
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        </head>
        <body>
            <input type="datetime-local" id="fecha">
            <p id="msg"></p>
            <script>
            $(document).ready(function(){
                $("#fecha").focus(function(){
                    $('#msg').html('');
                });
                $("#fecha").blur(function(){
                    var hoy = new Date();
                    var fecha = $('#fecha').val();
                    var fechaFormulario = Date.parse(fecha);
                    
                    if (hoy <= fechaFormulario) {
                        $('#msg').html("Fecha a partir de hoy");
                    } else {
                        $('#msg').html("Fecha pasado");
                    }
                });
            });
            </script>
        </body>
    </html>

I would recommend using the event blur instead of change . This way you will not skip the code before you finish filling in the date and time completely.

    
answered by 22.11.2018 в 00:27