I'm looking for a way to check and validate three input fields for date, month, and year individually using either jQuery or JavaScript. Can anyone

My form requires input fields for date, month, and year separately.

The validation rules are as follows: Date should be between 1-31 and month should be between 1-12. The desired date format is dd mm yyyy.

Could someone kindly help me with the HTML code below?

<div class="date"> 
  <input id="date" name="day" /> 
  <input id="month" name="month" /> 
  <input id="year" name="year /> 
</div> 

All input fields in the form are text boxes.

Answer №1

Simply engaging in some self-practice and hoping this can be beneficial

$('#submit').click(function(){
  var date = parseInt($('#date').val());
  var month = parseInt($('#month').val());
  var year = parseInt($('#year').val());
  if (isNaN(date) || isNaN(month) || isNaN(year)) {
    alert('incorrect format');
    return false;
  } else {
    if (date > 31 || date < 1) {
      alert('invalid date');
      return false;
    } else if ((month==4 || month==6 || month==9 || month==11) && date ==31) {
      alert('invalid date');
      return false;
    } else if (month==2) {
     var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
      if (date> 29 || (date ==29 && !isleap))
      alert('invalid date');
        return false;
    }
    if (month > 12 || month < 1) {
      alert('invalid month');
      return false;
    } 
    if (year > 2050 || year < 1900) {
      alert('invalid year');
      return false;
    } 
  }
  $('#myform').submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="" id="myform" method="POST">
<label for="date">Date</label>
<input type="text" id="date" name="date" />
<label for="month">Month</label>
<input type="text" id="month" name="month" />
<label for="year">Year</label>
<input type="text" id="year" name="year" />
<input id="submit" type="submit" value="Submit">
</form>

Source:

Answer №2

Here is a script you can try:

<script>
    function validateForm() {
        var d = document.forms["myForm"]["date"].value;
        var m = document.forms["myForm"]["month"].value;
        var y = document.forms["myForm"]["year"].value;

        if(d == null || d == ""){
            alert("Please select date.");
            return false;
        }
        if(m == null || m == ""){
            alert("Please select date.");
            return false;
        }
        if(y == null || y == ""){
            alert("Please select date.");
            return false;
        }
        if((m == 4 || m == 6 || m == 9 || m == 11) && d == 31) {
            alert("Selected month contains only 30 days.");
            return false;
        }
        if(m == 2 && d > 29 && (y%4 == 0)) {
            alert("Selected month contains only 29 days.");
            return false;
        }

        if((m == 2) && d > 28) {
            alert("Selected month contains only 28 days.");
            return false;
        }
        return true;
    }
</script>

Below is the form structure:

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post"> 
<input type="number" id="d" name="date" min="1" max="31" />
<input type="number" id="m" name="month" min="1" max="12" />
<input type="number" id="y"  name="year" min="1900" max="9999" />
<input type="submit" value="Submit">

</form>

Answer №3

Hey there!! I have just developed a form with three text fields for day, month, and year validation using JavaScript.


        <script type="text/javascript">
            function dateChecker()
            {
            var dayValidate = "([1-9]|[12]\d|3[01])";
            var monthValidate = "^(0?[1-9]|1[012])$";
            var yearValidate = "/^(19[5-9]d|20[0-4]d|2050)$/";
            var days = document.getElementById('dayId').value;
            var months = document.getElementById('monthId').value;
            var years = document.getElementById('yearID').value;

            if (!days.match(dayValidate))
            {
                alert("Please, Enter Days  between 1 to 31 ");
                document.form1.dayId.focus();
                return false;
            }

            if (!months.match(monthValidate))
            {
                alert("Please, Enter Months in between 1 to 12 ");
                document.form1.monthId.focus();
                return false;
            }

            if (!(+years >= 1900 && +years <= 2016))
            {
                alert("Please, Enter Years in between 1900 to 2016 ");
                document.form1.yearID.focus();
                return false;
            }

        }


       </script>

       <form name="form1">
        <table>
            <tr>
                <td>
                    <input type="text"  id="dayId"/> 
                </td>
                <td>
                    <input type="text"  id="monthId"/> 
                </td>
                <td>
                    <input type="text"  id="yearID"/> 
                </td>
            </tr>
            <tr>
                <td>
                    <input type="submit" onclick="returndateChecker();"/>
                </td>
            </tr>
        </table>
    </form>

Answer №4

To implement this feature, you can utilize the input boxes in the following manner:

<input type="number" name="day" min="1" max="31" />
<input type="number" name="month" min="1" max="12" />
<input type="number" name="year" min="1900" max="9999" />

Alternatively, a more streamlined approach would be to use a date field:

<input type="date" name="date" id="date">

You can then extract the day, month, and year values as needed for further processing.

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

perform validation middleware following completion of validation checks

Looking to establish an Express REST API, I aim to validate both the request parameters and body before invoking the controller logic. The validation middleware that I have put together is as follows: const { validationResult } = require('express-va ...

Encountering a Module not found error with a ValidationError when trying to import an SVG file within a React

I've set up a manual Webpack 5 configuration for my React project with TypeScript. I am facing an issue while trying to import an SVG icon and using Material UI in the project. The error message I'm encountering is: Module not found: ValidationEr ...

Error message indicating that Element <> cannot be scrolled into view persisting despite attempting common troubleshooting methods

Currently, I am utilizing Selenium to create a web scraper for downloading multiple podcast episodes from Spreaker. # https://www.spreaker.com/show/alabamas-morning-news-with-jt for i in range(3): print("Click number: {}".format(str(i))) see_mor ...

Customizing the size of the selectInput widget in R/Shiny

I'm trying to adjust the size of the selectInput() widget in shiny using selectize.js. I've attempted to tweak various attributes listed on this page (https://github.com/selectize/selectize.js/blob/master/dist/css/selectize.css) but I can't ...

Troubleshoot: Why is my AngularJS bootstrap.ui modal failing to

I am experiencing an issue with displaying a modal dialog using AngularJS bootstrap.ui. After calling $modal.open(...), the screen grays out, the HTML from my templateUrl is fetched from the server, but the modal does not appear. When I click on the gray a ...

Rendering on the server with React: Utilizing server-side rendering to display product information with passed-in :productId parameters

Having an issue with my React app that is rendered on both the client and server (Node and Express). When someone types in the URL directly, the application crashes because it cannot parse the '1' in the URL to fetch the correct product. If a l ...

Achieving optimal hardware performance for WebGL compatibility is essential

Lately, I have been exploring the world of Three.js to create impressive 3D scenes in WebGL. To ensure compatibility for all users, I have also developed versions using Three's CanvasRenderer which may not be as detailed but can still function on brow ...

It appears that Yarn is having trouble properly retrieving all the necessary files for a package

Recently, I encountered a strange issue in our project involving 3 microservices, all using the exceljs library. Two of the microservices successfully download all necessary files for this package through yarn. However, the third microservice is missing ...

What is the best way to compress the div and its contained text while still maintaining responsiveness?

When I got home from work, I decided to create a website similar to the attached image. However, I encountered an issue with styling the "TECHNOLOGY" div in the top right corner and making it responsive while staying within the parent div. Additionally, an ...

Is there an issue with how my JavaScript code is formatted?

Working on a .NET MVC2 project, I have included SomeClass.Home.js and jQuery in the masterpage. The content of my SomeClass.Home.js file is as follows: SomeClass.Home = {}; $(document).ready(function () { SomeClass.Home.SomeMethod(); }); SomeClas ...

Leverage a JavaScript function to manipulate the behavior of the browser's back button

Is there a way to trigger the Javascript function "backPrev(-1)" when the back button of the browser is clicked? Appreciate any help, thank you. ...

Why is the PHP response always 0 even though AJAX JSON data is being sent correctly during Wordpress plugin development?

There seems to be a simple issue here that I'm missing. The data is being sent correctly according to Firebug in the NET tab (NET tab-> Post -> Parameters). However, the PHP function does not even echo simple text. This is the PHP code: add_ac ...

Vue transition not functioning properly when hovering over text for changes

When you hover over the circular region on the website, the text and description in the red box will change. To add a fade animation effect when the text changes, I attempted to use <transition> as per the documentation provided in this link. Unfor ...

enclose code within square brackets

I have a shortcode function that currently works with or without square brackets. However, I would like it to only work with square brackets. shortcode (Current) itemText num="1" title="This is a title" shortcode (Desired) [itemText n ...

Exploring the Collection of Key-Value Pairs within a JSON Data Structure

Within my JSON object, I have a comprehensive list of unique product variant combinations generated by Woocommerce. Let's illustrate this with an example: a product is available in 2 sizes (size1 and size2) and colors (color1 and color2). variant_lis ...

What could be causing the hover style to not take effect on the leaf nodes in jQuery Treeview?

Upon reviewing Sample 1 on this specific page, you may notice that the text turns red when hovering over the folder entries, but not for the leaf entries. My goal is to have the styling for the leaf entries mimic the behavior of the folder entries. Each b ...

What is the best method to center a div on the screen?

Is there a way to have a div open in the center of the screen? ...

The Consequences of Using Undeclared Variables in JavaScript

What is the reason behind JavaScript throwing a reference error when attempting to use an undeclared variable, but allowing it to be set to a value? For example: a = 10; //creates global variable a and sets value to 10 even though it's undeclared al ...

API for Google Maps

Recently, I've been working on integrating Google Maps into my webpage. I successfully created a map that fills up 100% of the screen on its own HTML page. Now, I want to include a smaller version of the map within a div on my website. The include() f ...

Utilize Apollo to retrieve a variety of queries at once

Currently, I'm utilizing nextJS for my frontend development along with Apollo and GraphQL. For fetching queries, I am using the getStaticProps() function. To enhance modularity and maintainability, I have segmented my queries into multiple parts. The ...