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/

Jeff
  • 12,555
  • 5
  • 33
  • 60
computer
  • 113
  • 1
  • 2
  • 12
  • 1
    attach an event listener to those inputs....? – NewToJS Dec 16 '16 at 00:24
  • 1
    Your question is not clear. update your question in detail – Venkat.R Dec 16 '16 at 00:32
  • How do you account for invalid dates? – RobG Dec 16 '16 at 00:42
  • 1
    What are you asking? – jdmdevdotnet Dec 16 '16 at 00:44
  • http://jsfiddle.net/Ttsa8/5/ the code to check the dates – computer Dec 16 '16 at 00:45
  • @AlGoreRhythm I am trying to get the java script to work which when submit button it will try to validate the age with the code given and if its over 18 years old it'll then post the details to PHP – computer Dec 16 '16 at 00:47
  • 1
    What does your code currently do? What's the problem? – qxz Dec 16 '16 at 01:05
  • @qxz my current code work like this. After user enter the number in each individual boxes and click submit it will then validate using the code given above. The problem is even tho when it checks user is below 18 its shows an alert "below 18" and it suppose to terminate but in my case it still submit the form – computer Dec 16 '16 at 01:09
  • See ["prevent form submission (javascript)"](http://stackoverflow.com/questions/24248576/prevent-form-submission-javascript) – qxz Dec 16 '16 at 01:13

1 Answers1

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>
Zoltán Süle
  • 1,482
  • 19
  • 26
  • Using this idea how should i implement - if true then submit/post to PHP – computer Dec 16 '16 at 01:35
  • 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. – Zoltán Süle Dec 16 '16 at 01:51
  • @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) – Zoltán Süle Dec 16 '16 at 22:40