A guide to verifying a user's age using JavaScript by collecting information from 3 separate input fields

On page load, only the year input is required for users to fill in. The user can enter their birth year first without providing the month and day.

Currently, I have a function that checks if a person is over 16 years old by comparing their birth year with the current year.

checkAge() {
    let yearOfBirth = new Date().getFullYear() - this.form.dobYear;

    if (yearOfBirth > 16) {
      this.isSixteen = false;
      this.belowSixteen = false;
    }
}

If the age equals exactly 16 when subtracting the user's input birth year from the current year, then two select elements will display for the user to choose the day and month of their birthday.

In this scenario, it is important to accurately determine whether the user is precisely 16 years old or potentially a few months away from turning 16. This distinction will affect how their age is displayed.

I am utilizing BootstrapVue and Vue.js for this functionality.

Answer №1

Retrieve the current Date

var currentDate = new Date();

Subtract 16 years from it

currentDate.setFullYear(currentDate.getFullYear() - 16);

Create a new Date object based on user input

var userInputDate = new Date(y, m, d);

Compare the two dates

if(userInputDate.getTime() <= currentDate.getTime()) {
  // ok
} else {
  // not ok
}

function verifyAge(event){
  var currentDate = new Date();
  result.innerText = "Current date: "+ currentDate;
  currentDate.setFullYear(currentDate.getFullYear() - 16);
  result.innerText += "\n16 years ago it was: " + currentDate;
  var birthday = event.target.valueAsDate;
  if(birthday)
    result.innerText += "\nVerdict: "+ (birthday.getTime() < currentDate.getTime() ? "Okay" : "Too young");
}
Birthday: <input type="date" onchange="verifyAge(event)" value="0"><br>
<div id="result"></div>

Answer №2

To determine the year only:

function findYearDifference(y){ // input birthday year
   return (new Date()).getUTCFullYear() - y;
}

^This function calculates the difference in years between the current date and the provided year.

To calculate the full age based on birthday:

function calculateFullAge(y,m,d){ // input birthday year, month, day
   var birthday = new Date(y + '-' + m + '-' + d);
   var ageMsDiff = Date.now() - birthday.getTime();
   var ageDate = new Date(ageMsDiff);
   return Math.abs(ageDate.getUTCFullYear() - 1970);
}

^This function determines the total number of years between a specified birthday and the current date.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you provide an explanation for what the line "const { Nuxt, Builder } = require('nuxt')" is doing in this

Currently, I am working on a Nuxt project where I will be utilizing the Express framework on the server side. Upon setting up the Nuxt project and choosing the express option, I came across a new file named server/index.js which includes a basic template f ...

Unforeseen Problem: Mocha ES6 Node App Glitch

Encountering an ES6 import issue in Mocha test cases currently. Even after attempting to add the latest Babel and presets, the issue remains unresolved. Various solutions have been tested but none seem to fix the problem. This snippet shows my package.jso ...

Error Loading Collada Texture: Three.js Cross Origin Issue

I'm encountering an issue with loading a Collada file using three.js that has a texture called Texture_0.png associated with it. The Collada file and the texture are stored in the same blob and accessed via a REST Web Service. CORS is enabled, allowin ...

A guide on showcasing items on an html webpage through the use of javascript

Currently, I have a series of hardcoded HTML elements in my code snippet. <!-- Reciever Message--> <div class="media w-50 ml-auto mb-3"> <div class="media-body"> ...

What is the best way to retrieve class members using component properties?

I am looking to implement a mixin for setting the header and meta data in my project. I recently discovered vue-meta, which seems to work really well for this purpose. However, I am still getting acquainted with TypeScript and class-based components. How ...

Use Onblur and Onfocus events in an input field that is read-only

Here is an input field: <input class="" type="text" id="Name_11_1" name="Name" value="Your name:"> I would like to modify it as follows: <input class="" type="text" id="Na ...

Proceed to the next request after the initial request has finished executing in node

Imagine there is an endpoint called /print. Each time a request is sent to this endpoint, it triggers the function printSomething(). If another user hits this endpoint while printSomething() is still processing, it will run the function again simultaneousl ...

Error 404 occurred when trying to access the webpack file at my website address through next js

Check out my website at https://i.stack.imgur.com/i5Rjs.png I'm facing an error here and can't seem to figure it out. Interestingly, everything works fine on Vercel but not on Plesk VDS server. Visit emirpreview.vercel.app for comparison. ...

Issue with Electron-vue: 'compute:' not functioning as expected

My attempt to create a simple example using the element-ui library was not successful. There are two 'switches' with different active state values: 2 and 1. The values of the switches are supposed to be displayed in <p>{{sw1}}</p> and ...

`Can controllers be included in route or template definitions?`

When it comes to defining a route with a template, there are two main ways to set the controller for the view: In the route: $routeProvider .when('/phone/:phoneId', { controller: 'PhoneDetailController', templateUrl: &ap ...

Display the verified user in a Vuejs interface

I followed a tutorial on Laravel 5.3 and Vue 2.0, but I'm encountering an issue: Link to Tutorial Video Products.vue: <my-product :key="product.id" v-for="product in products" :authenticatedUser="authenticatedUser" ...

Generating a dynamic sitemap with Next.js

I have been working on a project where I need to create a sitemap, and I am currently using next-sitemap for generation. However, I've encountered an issue with this method, as well as other solutions I've come across, because the sitemap is only ...

Issue with Knockout.js: Parsing error in bindings - SyntaxError: Unexpected token `};`

Take a look at this example. I've tried to simplify it as much as possible, but I'm still struggling to figure out where I went wrong. Any help would be greatly appreciated )) P.S Stack Overflow requires code, not just a link to jsfiddle. H ...

Applying custom hover color to Vue components based on props

I am facing a challenge where some of my single-file components need to inherit hover color from props. To address this issue, I have come up with a solution where I set CSS variables in the mounted method: <template> <div class="btnWrapper" ...

Guide on displaying link parameter information on a separate webpage using only JavaScript

While doing some research, I came across an issue. I have a page called specifications.html with three links: details.html?id=1, details.html?id=2, and details.html?id=3. My goal is to display the details of each link when someone clicks on it. For examp ...

Navigating between different views in a Vue application often involves passing data

I am currently using a <search-bar> component with dropdown options for filtering search results. When the submit button is pressed, the following code is executed: search() { let query = { status: this.selectedOrderStatus }; this.$rout ...

How to use the window.confirm method to print the HTML tag in an AJAX post

Is there a way to display a confirmation window for users who want to delete data from the database without including HTML tags like <strong> or <br />? I am currently using the confirm() function as follows: var str = document.getElementById ...

Having trouble with the line of code right before a $timeout in AngularJS

I am wondering about an issue in my code. vm.showSuccess = true; $timeout(function() { close(); }, 2000); vm.showSuccess = false; Interestingly, the timeout function is executing properly but the first line seems to be ignored. This piece of code is me ...

Unable to hide the mobile menu button

I am currently working on a fun website project . I am facing an issue with the mobile menu button not disappearing using display:none in Safari on my iPhone when in landscape mode, even though it works fine in Chrome. My goal is to make the #menu-button ...

Submitting forms using Ajax within a modal pop-up box

Here's an interesting issue that I'm facing: On a test page, when the user clicks to view results, a modal box opens with 3 select boxes. Select Box 1 populates Select Box 2, which then populates Select Box 3 The Problem: After clicking submi ...