Is it possible to verify age on a date field in vanilla JavaScript?

How can I validate the age on a date input field? If someone is 18 or older, they will be valid. Otherwise, an error message should be displayed. Can you help me with this?

Answer №1

This script takes a birthdate input and stores it in a constant variable called b18. It then adds 18 years to the birthdate and compares it with the current date to determine if the person is at least 18 years old.

// const b contains birth date to be tested
document.querySelector("input").addEventListener("input",function(){

 const b=new Date(this.value);

 const b18=new Date(b.getTime());
 b18.setYear(b.getFullYear()+18);

 // alternatively you could calculate that "critical birthdate", 
 // 18 years ago, that makes you an adult today:
 const d18=new Date();
 d18.setYear(d18.getFullYear()-18);

 console.log(new Date()>b18,d18>b);
})
<input type ="date" value="2003-08-29">

Answer №2

Here is an example of how to achieve this:

        <input id="age" type="number" />


        let age = document.getElementById('age');
        let minAge = 21;

        age.onchange = () => {
            if(!age.value >= minAge){
                    age.style.border = "1px solid red";
                } else if(age.value >= minAge) {
                    ​age.style.border = "1px solid green";
                }
        }
​

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

What is the best way to combine a string with a $scope variable in AngularJS?

Is there a way to add a variable to the $scope model in order to concat it? I'm attempting this code: for(var i=0; i<=response.length-1; i++) { $scope.formData.jobId+i = response[i].jobId; } How can I combine the variable i with $scope.formDat ...

Showing real-time information from an object

I am attempting to showcase the 'helpText' data on the front end based on the type. Is it feasible to include a conditional statement (metricsType variable) and the [key] value into what I want to return? The final 'p' below provides an ...

Having trouble viewing the image slider on an HTML webpage

I've been attempting to incorporate an image slider into my personal website on GitHub, but I've encountered some difficulties as the images are not displaying. Interestingly, I can load individual images without using the slider and they show up ...

Is the $http call for OPTIONS instead of POST?

Hey there, I'm encountering a strange issue while trying to call my backend using the POST method. Remote Address:192.168.58.183:80 Request URL:http://192.168.58.183/ESService/ESService.svc/CreateNewAccount Request Method:OPTIONS Status Code:405 Meth ...

The JQuery datepicker fails to function properly when the input field is modified from read-only

Utilizing the datepicker in conjunction with an MVC3 application. I aim to keep the input field as readonly until triggered by an edit button. Upon focusing on the field, I want the datepicker functionality to be activated. The code snippet below functio ...

What is the simplest method for transferring data to and from a JavaScript server?

I am looking for the most efficient way to exchange small amounts of data (specifically just 1 variable) between an HTML client page and a JavaScript server. Can you suggest a script that I can integrate into my client to facilitate sending and receiving d ...

The jQuery load() method may not load all elements

I've been struggling with a query issue for quite some time now. I have a Content Management System that I want to integrate into my website, but unfortunately, I am unable to use PHP includes. As an alternative, I decided to utilize jQuery instead. D ...

When transitioning to an object, Vue.js fails to refresh

My component contains an object called elements: elements: { id: { text: '', color: '', ... } To modify it, I use: <a-textarea autoFocus placeholder="text to include" :style="{ width: &ap ...

Tips for eliminating default classes from Mui Typography styling

I’ve been working on creating a Typography element and noticed some default MUI CSS classes added when debugging in the browser. I attempted to disable them by using empty arrays at the end of the sx prop, but it did not work as expected. In the image p ...

stopping action when hovering

Looking for some assistance with my javascript function that scrolls through an array of images on a set interval. I want to enhance it by pausing the rotation when hovering over any of the images. Javascript (function() { var rotator = document.getE ...

How can I retrieve information from an HTML or JavaScript object?

Imagine a scenario where you have an HTML table consisting of 5,000 rows and 50 columns, all generated from a JavaScript object. Now, suppose you want to send 50 checked rows (checkbox) from the client to the server using HTTP in JSON format. The question ...

Obtain a compilation of users who have expressed their reaction to a message with a specific emoji on Discord

Check out this Discord.js code snippet for a Discord bot: client.channels.fetch('channelID here').then(function (channel) { channel.messages.fetch('messageID here').then(function (message) { console.log(message.reactions.cache.get(&a ...

Where did my HTML5 Canvas Text disappear to?

I am encountering a common issue with my code and could use some guidance. Despite numerous attempts, I can't seem to figure out why it isn't functioning properly. To better illustrate the problem, here is a link to the troublesome code snippet o ...

"Retrieving Data Using jQuery's .ajax Method in Visual Basic

<WebMethod()> Public Shared Function gtet() As String ... Dim GET = uClass.GetSets(dbuser, dbparam1) ... End Function and $(document).ready(function () { data = { }; var jsondata = $.toJSON(data); $.ajax({ type: "GET ...

Understanding requestAnimationFrame and how it helps in achieving a smooth framerate

I stumbled upon this helpful code snippet that calculates the frame rate for an animation I created. Can someone please explain how it works? Check out the code below: <script src="jquery.js"></script> window.countFPS = (function () { var ...

Preventing multiple tabs in a form with PHP

I have successfully used JavaScript to prevent a link from being opened in multiple browser tabs every time a user clicks on it. For example, if the destination of my link is Google, it will create a new tab if one does not already exist but refresh the ex ...

Pattern for Ajax callback in Javascript

I'm facing an issue with the code snippet below. var bar = { ajaxcall : function(){ var _obj = {}; $.ajax({ headers: { 'Content-Type': "application/json; charset=utf-8", 'da ...

Utilize specific Angular JS methods just a single time

In my Angular application, I have the following architecture: Index Page -> Shell Page -> User view (User can open subview from here) Every route change in my application goes through the Shell page. There is a function on the Shell page called activate ...

Is there a javascript file storing an image?

Currently, I am in the process of creating my personal portfolio website and incorporating react-bootstrap for designing my react components. I have been attempting to add an image using the Image component provided by react-bootstrap. However, I noticed ...

The JavaScript function for clearing an asp.net textbox is not functioning properly

I am working on an ASP.net project and have encountered an issue with two textboxes. When one textbox is clicked on, I want the other one to clear. Below is the code I have for the textboxes: <asp:TextBox runat="server" ID="box1" onfocus="clearBox2()" ...