简体   繁体   中英

Javascript - Form submits with required field left empty

EDIT: I worded my question wrong. If I leave the required DOB field empty, it says 'Welcome' which I want it to say only if the users DOB suggests they are over 17. After it says welcome, it then tells me to fill out the required DOB field. Why is it still saying welcome when no DOB is entered?

Here's all the code I think is relevant:

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!");

}

You could use javascript to detect an empty date field and send an alert.

Modifying the javascript should work. Try something like this:

function calcAge(birthDate) {
  todaysDate = new Date(today);
  /*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 givenDOB = document.getElementById('dateof').value;
  if (givenDOB == "") {
    alert("Sorry, you must enter your date of birth!");
  } else {
    var age = calcAge(givenDOB);
    if (age < minAge) {
      alert("Sorry, the minimum age is 17!");
    } else
      alert("Welcome!");
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM