Javascript Validates Date of Birth and Block Same Year

Asked

Viewed 425 times

1

I need a Javascript that Block put date with the same current year. For Date of Birth Field. Someone can help me?

Out in the field:

<div class="col-sm-4">
                                        <label for="dataNasc" class="control-label"> Data de Nascimento</label>
                                        <input type="date" class="form-control" name="dataNasc" id="dataNasc"/>
                                    </div>
  • You have tried using the Jquery UI datepicker or where you use it you cannot use it? https://jqueryui.com/datepicker/

  • It is not javascript, but you can manually put: <input type="date" name="bday" max="2016-12-31"> the attribute max

  • I’ve thought about it, but I need something more automatic.

  • I already automated in the answer below.

2 answers

2

 var data = new Date(new Date().getFullYear() - 1, 11, 31).toISOString().slice(0,10);
document.getElementsByName("dataNasc")[0].setAttribute("max", data);
<div class="col-sm-4">
                                        <label for="dataNasc" class="control-label"> Data de Nascimento</label>
                                        <input type="date" class="form-control" name="dataNasc" id="dataNasc"/>
                                    </div>

1


Let’s say you have this in HTML:

<input type="text" id="date_start">

In javascript we have this:

var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var fSDate = new Date(y, m, 1);
var fEDate = new Date(y - 1, m + 1, 0);

$.datepicker.setDefaults({
    changeMonth: false,
    changeYear: false,
    showOtherMonths: false,
    yearRange: '-0:+0',
    dateFormat: 'yy-mm-dd',
    defaultDate: +0, //30 days ago
    numberOfMonths: 1,
    minDate: fSDate, 
    maxDate: fEDate,
    showAnim: 'fadeIn',
    showButtonPanel: false
});

$('#date_start').datepicker();

Pay attention to the fSDate and fEDate and notice how you can set the limits for the year, month and day using a little logic. I’ve already subtracted a year from the fEDate and it will only show at the latest 2016.

Behold this online example in Jsfiddle. This example is great for you to see everything you can change until you get the desired result. Play a little with this Fiddler until you master this one datepicker().

  • Perfect! Thank you!!

  • Good, that was my first response here in the O.R.

Browser other questions tagged

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