0

In my form, I have these elements [day][month][year] which enables user to enter

<form id="mail" action="form.php" method="post" onsubmit="validateForm()">
    <label for="dateOfBirth">Date of Birth</label>
     <input type="number" id="day" name="day" max="31" placeholder="Day" >
     <input type="number" id="month" name="month" placeholder="Month" max="12" >
     <input type="number" id="year" name="year" placeholder="Year" max="2016"/>
    <input type="submit" value="submit">
    </form>

When the submit button is pressed, it should check if user is over 18 or not. If he is over 18, the form should submit. If the user is not over 18, it should display an error. The code to validate age is working, the only thing is that I am not sure how should I place my code

   var day = getElementById("day").value;
   var month = getElementById("day").value;
   var year = getElementById("day").value;
   var age = 18;
   var mydate = new Date();
   mydate.setFullYear(year, month-1, day);

   var currdate = new Date();
   var setDate = new Date();         
   setDate.setFullYear(mydate.getFullYear() + age, month-1, day);

   function validateForm() {

    if ((currdate - setDate) > 0){


        preventDefault();                               // Prevent it being sent
        var details = $('#mail').serialize();         // Serialize form data
        $.post('form.php', details, function(data) {  // Use $.post() to send it
        $('#mail').html(data);                    // Where to display result
    });

        alert("above 18");
    }else{

        alert("below 18");
        $("form").submit(function(e){
            alert('submit intercepted');
            e.preventDefault(e);
        });
    }
}

Code to check age http://jsfiddle.net/Ttsa8/5/

9
  • 1
    attach an event listener to those inputs....? Commented Dec 16, 2016 at 0:24
  • 1
    Your question is not clear. update your question in detail Commented Dec 16, 2016 at 0:32
  • How do you account for invalid dates? Commented Dec 16, 2016 at 0:42
  • 1
    What are you asking? Commented Dec 16, 2016 at 0:44
  • 1
    What does your code currently do? What's the problem? Commented Dec 16, 2016 at 1:05

1 Answer 1

1

if you want to calculate the age between the date input field (day, month, year) and the current time then you can do it this way by jquery.
It will check the age when you change the value of the fields or when you submit the form.
The idea was based on this.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>calculates the age between the date input fields and the current time</title>
    <meta charset="utf-8">

    <script
            src="https://code.jquery.com/jquery-3.1.1.min.js"
            integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
            crossorigin="anonymous"></script>
</head>

<body>

<form id="form">
    <label for="dateOfBirth">Date of Birth</label>
    <input type="number" id="day" name="day" max="31" placeholder="Day" >
    <input type="number" id="month" name="month" placeholder="Month" max="12" >
    <input type="number" id="year" name="year" placeholder="Year" max="2016"/>
    <input type="submit" id="mail" value="submit">
</form>

<script>

    function validate()
    {
        if (!$("#day").val()) {
            return false;
        }

        if (!$("#month").val()) {
            return false;
        }

        if (!$("#year").val()) {
            return false;
        }

        return true;
    }


    function calculateAge()
    {
        var ageLimit = 18;

        var day   = $("#day").val();
        var month = $("#month").val();
        var year  = $("#year").val();

        if (!validate()) {
            console.log('invalid form');
            return false;
        }

        todayDate  = new Date();
        todayYear  = todayDate.getFullYear();
        todayMonth = todayDate.getMonth();
        todayDay   = todayDate.getDate();

        diffYear = todayYear - year;

        if (todayMonth < (month - 1))
        {
            diffYear--;
        }

        if ((month - 1) == todayMonth && todayDay < day)
        {
            diffYear--;
        }

        if (diffYear >= ageLimit){
            // you are above 18
            console.log('above 18');
            return true;
        }

        console.log('below 18');


        return false;
    }

    $('#form').on('submit', function(e) {

        if (!validate()) {
            console.log('invalid form');
            return false;
        }

        if (calculateAge()) {
            // the post will happen here if the form is valid and it is above the age limit
            console.log('submit fired');
            return true;
        }
        console.log('submit blocked');
        return false;
    });

    $('#month').on('change', function(e) {
        calculateAge();
    });

    $('#day').on('change', function(e) {
        calculateAge();
    });

    // This is a shortcut for .on("change", handler)
    $('#year').change(function() {
        calculateAge();
    });

</script>

</body>

</html>
Sign up to request clarification or add additional context in comments.

3 Comments

Using this idea how should i implement - if true then submit/post to PHP
I changed the code. Check the $('#form').on('submit', function(e) {} routine. If you set the action of the form, it will submit the data if the form is valid and the age is above the limit.
@computer: I am curios whether it works for you this way? (don't forget to remove the console.log lines from the code, because they kill IE browsers)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.