In JavaScript, a form is submitted even when a required field is left blank

Revise: My question was not clear. If I do not enter a date of birth in the required field, it displays 'Welcome' when it should only say that if the age indicated by the DOB is over 17. Additionally, after displaying 'Welcome', it prompts me to fill out the required DOB field. Why does it continue to show welcome without an entered DOB?

Below is the relevant code snippet:

Date of Birth Field DOB:

<input type="text" name="Date" id="dateof" placeholder="YYYY-MM-DD" title="Enter your date of birth in the form YYYY-MM-DD" required /><br/><br/>

Date of Birth Validation Function

var minAge = 17;
var today = new Date()

function calcAge(birthDate, todaysDate) {
    todaysDate = new Date(today);
    var givenDOB = document.getElementById('dateof').value; /*date of birth entered*/
    var birthDate = new Date(givenDOB);
    var years = (todaysDate.getFullYear() - birthDate.getFullYear());

    if (todaysDate.getMonth() < birthDate.getMonth() ||
        todaysDate.getMonth() == birthDate.getMonth() && todaysDate.getDate() < birthDate.getDate()) {

        years--;
    }

    return years;
}


function setAge() { 

    var age = calcAge();
    if (age < minAge) {
        alert("Sorry, the minimum age is 17!");
    } else

        alert("Welcome!");

}

Answer №1

If you want to create a javascript function that can detect an empty date field and trigger an alert, there is a simple solution:

Here's a modified version of the javascript code that should do the trick:


function calculateAge(dateOfBirth) {
  var todayDate = new Date();
  var birthDate = new Date(dateOfBirth);
  var years = (todayDate.getFullYear() - birthDate.getFullYear());

  if (todayDate.getMonth() < birthDate.getMonth() ||
    todayDate.getMonth() == birthDate.getMonth() && todayDate.getDate() < birthDate.getDate()) {
    years--;
  }

  return years;
}

function checkAge() {
  var inputDOB = document.getElementById('date').value;
  if (inputDOB == "") {
    alert("Please enter your date of birth!");
  } else {
    var age = calculateAge(inputDOB);
    if (age < 18) {
      alert("Sorry, you must be at least 18 years old!");
    } else {
      alert("Welcome!");
    }
  }
}

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

The program encountered an error stating: "require variable not found at"

I am facing an issue while using jasmine with Grunt. Every time I run my jasmine tests, I encounter the following error: ReferenceError: Can't find variable: require at In my Gruntfile.js, this is how I have configured jasmine: jasmine: { js: ...

Exploring the wonders of Backbone fetch and mastering the art of handling the jqXHR object

Currently, I am working on developing a new application using Backbone. Unfortunately, the backend APIs have not been written yet, so I am attempting to work with a JSON data file that is local to my project. Setting its location as the urlRoot allows me t ...

Is it possible for me to modify the Event Listener functionality of PayPal buttons to trigger a hidden surprise, and then revert it back to its original settings afterwards?

I am currently working on implementing a fun easter egg feature on my website that will activate when a specific donation amount is entered. Is there a way to customize the behavior of the PayPal button so that instead of redirecting to the standard PayPa ...

Retrieve the content from a textarea and insert it into a different textarea with additional text included

Users can input HTML codes into a textarea named txtar1. A 'generate' button is available; Upon clicking the 'generate' button, the content of txtar1 will be transfered to another textarea named txtar2 with additional CSS code. Here&ap ...

What steps should I take to fix the WCF / AJAX problem I'm encountering? (Receiving a 400 Bad Request error

I am relatively new to AJAX and JavaScript, so I appreciate your patience. My goal is to use an AJAX call to send a new user object to a WCF C# method, which will then create the user in a SQL server database. Subsequently, the C# method will send back a v ...

Incorporate Web-GL sandbox effects into an HTML webpage

I am searching for a method to showcase a Web-gl shader obtained from GLSL Sandbox on the background of an HTML page. Yet, it seems there is no simple embeddable API available. How can I accomplish this task? Can I integrate this specific Shader into an H ...

What are all the functionalities provided by jquery select?

Currently, I am venturing into testing out a new jQuery plugin. let myPlugin = new MyPlugin(); $(#myPlugin).someFunction(); console.log($(myPlugin)) I'm curious - is there a way for me to see a full list of the available functions/methods for me to ...

Angular form submission results in receiving an object instead of a simple value

While building a basic Angular form, I am encountering an issue where instead of retrieving the form value upon submission using onsubmit, I am getting an object as the value. Side Note: I have included some sample code for reference. Could you please ad ...

Connect-busboy causing NodeJS issue: TypeError - the method 'on' cannot be called on an undefined object

Recently I encountered an issue with a piece of my code: router.route("/post") .get(function(req, res) { // ... }) .post(authReq, function(req, res) { // ... // Get uploaded file var fstream; req.pipe(re ...

Is there a way to reverse the upside-down text generated by OffscreenCanvas.getContext().fillText()?

When using OffscreenCanvas.getContext().fillText() to generate text and then OffscreenCanvas.transferToImageBitmap() to create a map, I noticed that the text appeared flipped upside down when applied as a texture in a threejs project. The image clearly sho ...

Unable to delete touchmove event - Vue watching system

Preventing scrolling on mobile devices: const stopScroll = function(e) { e.preventDefault() } Adding the listener: document.body.addEventListener('touchmove', stopScroll, { passive: false }) Removing the listener: document.body.removeEvent ...

Upcoming verification with JSON Web Token

I am looking to incorporate JWT auth into my Next app. Currently, I have mapped out the flow as such: User enters email and password to log in Server responds with status 200 and a jwt access token in httpOnly cookies My main dilemma lies in deciding on ...

The Safari extension is launching as a file within Safari browser version 5 on a Mac running the Snow Leopard operating system

I recently ventured into the world of Safari extension development. After creating an extension using Extension Builder, I packaged and uploaded it to a server. On my website, I provided a download link for the extension: <a href="http://example.com/ex ...

How can I determine in JQUERY when all ajax requests on a page have finished processing?

Is there a way in JQUERY to determine when all ajax calls on a page have finished? I need to run a specific method once all the ajax calls are done. ...

Angular - No redirection occurs with a 303 response

Having an issue with redirection after receiving a 303 response from a backend API endpoint, which includes a Location URL to any subpage on my site. Upon attempting the redirect, an error is triggered: Error: SyntaxError: Unexpected token '<&ap ...

Do I require a post route for submitting a Form Action Post to an API?

I have implemented the npm package "twit" in my project to manage Twitter Status Updates. I have a form where users input their tweet, and upon submitting the form, a post request is sent to the path home/tweet/. Within my express router, I have defined a ...

I'm having trouble adding a background image, even though I have set it to static. What could be

I attempted to add a background image to my Django website, but unfortunately, it was not successful. I followed the steps provided in this Stack Overflow answer here, however, it did not work. I even made changes to the database by migrating them, but s ...

Javascript floating navigation toolbar

How can I create a minimalist launch bar with a search button that only appears on a page when a specific hotkey is pressed? I want to avoid using large libraries like mootools or FancyBox for this Chrome Extension project to keep it lightweight. Do you ...

problem with jquery object compatibility in ie9 and opera

I've been working on a script for my website that functions properly on Chrome, Safari, and Firefox. However, I'm running into issues with IE 9 (even in compatibility mode) and Opera. Am I missing something? Below is the Script: $(document).rea ...

Determining the selected option's value made by the user

On my index.php file, which contains the form and function, I have the following code: $(function() { $.ajax({ type: "POST", url: "invtype.php", data: "getrevenuetype=true", success: function(b){ $("#revenue ...