data type input only accept date greater than 18 years

Asked

Viewed 2,100 times

1

How do I put a condition within the input type date so it only accept dates older than 18 years, I was wondering if it has a condition to lock the input for dates older than 18 years, is for a form where only over 18 can send the form.

<label for="txtData_Nasc">Data de nascimento:</label>
<input type="date" class="form-control" id="txtData_Nasc" name="txtData_Nasc" required>
  • it would be more convenient for you to leave the "free" field and check your code by comparing the dates, if the user is under age you display a message.

  • You can do this without having to update the page?

  • with javascript yes.

  • How would I do? I’m beginner and I’m starting in this area now.

  • Take a look here @Evertonfigueiredo

2 answers

2


Elements of the type <input date... accept the attribute max, however you will need to somehow calculate the minimum date of birth based on the current date to assign this value, example:

Based on today’s date (23/03/2017) the minimum date should be (23/03/1999), so you should put this value in the min attribute of the element in the format AAAA-MM-DD.

<form>
<label for="txtData_Nasc">Data de nascimento:</label>
<input type="date" class="form-control" id="txtData_Nasc" name="txtData_Nasc" max="1999-03-23" required>
<input type="submit"/>
</form>

To calculate the date automatically as php in this case:

<label for="txtData_Nasc">Data de nascimento:</label>
<input type="date" class="form-control" id="txtData_Nasc" name="txtData_Nasc" max="<?php echo date('Y-m-d', strtotime('-18 year')); ?>" required>

Example date calculation in Ideone

  • 1

    Not one of the two examples worked here. :/

  • 1

    @Evertonfigueiredo I changed the max for min :P, actually the attribute that should be used is max. see if the example works now.

  • 1

    Thanks is working 100% @abfurlan

  • There is a problem, if the user type age still picks up for example year 2000.

  • @Evertonfigueiredo if type yes, but if you try to send the form will appear a message, do the test in the example above type the date and click send.

  • 1

    Really, sorry to bother you.

Show 1 more comment

0

You can perform the validation in the client through javascript, but I recommend that in addition to the client also perform the validation in the server (PHP). In the Onblur input event you can call the function that will validate.

<input type="date" class="form-control" id="txtData_Nasc" name="txtData_Nasc" onblur="validaIdade()">

to create the function that validates the age you can follow the following example: Javascript age validation

Browser other questions tagged

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