Check if input date javascript

JavaScript: Form Validation: Date and Time

When capturing information for insertion into a database, or use in other processing, it’s important to control what the user can enter. Otherwise you can end up with values in the database that have no relation to reality.

Checking for valid format

In this example, the date fields will only accept input that matches the pattern ‘dd/mm/yyyy’ (this could just as easily be changed to ‘yyyy-mm-dd’ or ‘mm/dd/yyyy’). The time field will allow input starting with ‘hh:mm’ following by an optional ‘am’ or ‘pm’. The fields can also be empty.

The code behind the form is as follows:

For each field in the form (first the dates, then the time field), a check is made as to whether the input is blank. If not, the input is compared to the regular expression. The expressions use a pre-defined class \d which represents any numeric character (0-9).

If you wanted to be really finicky the regular expression to match a date could also be written as:

If the input doesn’t match the regular expression then an error message is presented, the routine stops the form from submitting by returning a false value and the focus is moved to the relevant form field.

Читайте также:  Commenting methods in java

If all tests are passed, then a value of true is returned which enables the form to be submitted.

This routine DOES NOT check that the date or time input values are valid, just that they match the required format (d/m/y and h:m). Read further for more comprehensive checking.

Checking that input values are within bounds

Once you’re in control of the input format, it’s a lot easier to check that the values are actually valid. The function has been improved now so that the day, month and year values are checked to ensure that they’re in the right ball-bark (ie. 1-31 for the day and 1-12 for the month). Also the year must be between 1902 and the current year.

The year limitation would be used if you were asking for a date of birth or date of some recent event. If you’re setting up a calendar of future events you would check that the year is the current year or greater.

The code behind the form now is as follows:

If you’re not already familiar with regular expressions, then this might be getting a bit complicated. Basically, for each of the regular expression tests, an array is returned holding each component of the pattern that we’ve matched.

For example, when the date is checked, the return value, regs, is an array with elements 1 through 3 containing the day, month and year components of the input string. For the time check, the array returned includes the hour (pos 1), minutes (pos 2) and, optionally, the am/pm string (pos 3).

Each of these values is then tested against an allowed range (days: 1 — 31; months: 1 — 12; years: 1902 — 2023; and so on).

This script only confirms that the input format is correct and that each individual value falls within its allowed range. It does not check for leap years or invalid dates at the end of short months.

Modular checkDate() function

As we’ve seen before, creating re-usable functions can significantly reduce the size of your JavaScript code. These functions can even be included from an external javascript file so that the browser can cache them, and so the programmer isn’t always copying and pasting.

In this case, we’ve created a stand-alone functions which will validate a date field:

Dealing with alternative date formats is simple enough:

  • To convert to mm/dd/yyyy (US format) just swap regs[1] and regs[2] in the above code.
  • To convert to yyyy-mm-dd (European format) you need to change the regexp to /^(\d)-(\d)-(\d)$/ and swap regs[1] and regs[3].

This is explained again below.

Modular checkTime() function

And a function that will validate a time input:

Using these functions for validation

It’s now much easier to see what the main validation function is doing:

In each case the value passed to the function is the form field rather than the field value. The output will be almost identical to the earlier examples.

In this simple example we can even rewrite the checkForm function above as:

The associated HTML form would be as follows:

Adding HTML5 input validation

There’s now no excuse for having forms without HTML5 form validation attributes. Notably the pattern and required attributes which allow the browser to perform it’s own validation:

In practice most modern browsers will now use HTML form validation to preempt any JavaScript validation — with the notable exception of Safari.

Adjusting the code for different date formats

Visitors from some countries may find it confusing that we’re using the dd/mm/yyyy date format instead of the American or other standards. Modifying the code involves only minor changes:

US Date Format MM/DD/YYYY

In the checkDate function above you only need to replace references to regs[1] with regs[2] and vice-versa to reflect the change in order of the day and month values.

European Format YYYY-MM-DD

In the checkDate function above you only need to change the regular expression (re) to /^(\d)-(\d)-(\d)/ and then replace references to regs[1] with regs[3] and vice-versa as the year and day values have now changed position.

Checking month endings and leap years

In JavaScript to check for different month lengths, particularly for February in leap years, you need quite a bit of extra code. I’m not going to show that here, but you can find a link to get started under References below.

Instead we’re going to make use of Form Validation using Ajax to do some real-time checking using a server-side PHP script to get a definitive answer.

When you enter a date in the format dd/mm/yyyy the value is sent via an Ajax call to the server where it is validated using the PHP checkdate function.

The return value is displayed next to the input field:

Other actions could also be taken such as disabling form submission until there is a valid date.

The relevant portions of the HTML are as follows:

The JavaScript onchange event handler simply passes the date input value to a server-side script valid-date.xml.php where it will be tested. It then waits for an XML response containing instructions as to what message to display.

The PHP script valid-date.xml.php simply breaks up the date input string and passes the values to the built-in checkdate() function — which presumably knows all about leap years and other strange features of the Gregorian calendar:

else < die("Error: missing POST values"); >$date_is_valid = false; if(preg_match(«@(\d)/(\d)/(\d)@», $value, $regs)) < list($tmp, $day, $month, $year) = $regs; $date_is_valid = checkdate($month, $day, $year); >$retval = $date_is_valid ? «date $value is valid» : «date $value is not valid»; $xml = new \Chirp\AjaxResponseXML(); $xml->start(); $xml->command(‘setcontent’, [ ‘target’ => «rsp_$target», ‘content’ => $retval ]); if($date_is_valid) < $xml->command(‘setstyle’, [ ‘target’ => «rsp_$target», ‘property’ => ‘color’, ‘value’ => ‘green’ ] ); > else < $xml->command(‘setstyle’, [ ‘target’ => «rsp_$target», ‘property’ => ‘color’, ‘value’ => ‘red’ ]); $xml->command(‘focus’, [ ‘target’ => $target ]); > $xml->command(‘setstyle’, [ ‘target’ => «form1», ‘property’ => ‘cursor’, ‘value’ => ‘default’ ]); $xml->end();

You can copy the code for valid-date.xml.php from the box below:

The script ajaxresponsexml.php can be copied below:

Both files need to be saved in the same folder as your HTML page for the date validation to work — so you have four files in total — the original HTML file with the form, AjaxRequestXML.js, ajaxresponsexml.php and valid-date.xml.php.

Similar to this setup from another example:

With Ajax you can make use of more powerful server-side functions and don’t have to include large JavaScript libraries for validating dates and other values. Just be aware that it means more requests to the server which can be slower than downloading and running JavaScript code.

The AjaxRequest class is a simple one we’ve created and use on a number of projects. You can find the details in Web Services using XMLHttpRequest (Ajax) and related articles.

References

  • HTML HTML5 Form Validation Examples
  • HTML Validating a checkbox with HTML5
  • JavaScript Preventing Double Form Submission
  • JavaScript Form Validation
  • JavaScript Date and Time
  • JavaScript Password Validation using regular expressions and HTML5
  • JavaScript A simple modal feedback form with no plugins
  • JavaScript Counting words in a text area
  • JavaScript Tweaking the HTML5 Color Input
  • JavaScript Credit Card numbers
  • JavaScript Allowing the user to toggle password INPUT visibility
  • PHP Protecting forms using a CAPTCHA
  • PHP Basic Form Handling in PHP
  • PHP Measuring password strength
  • PHP Creating a CAPTCHA with no Cookies

Источник

Check if input date javascript

Last updated: Jan 14, 2023
Reading time · 3 min

banner

# Check if an Input type=»date» is Empty in JavaScript

Use the value property to check if an input type=»date» is empty.

The value property stores the date formatted as YYYY-MM-DD or has an empty value if the user hasn’t selected a date.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> label for="start">Input type Date:label> input type="date" id="date" name="trip-start" /> button id="btn">Checkbutton> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() const dateInput = document.getElementById('date'); if (!dateInput.value) console.log('Input type date is empty'); > else console.log('Input type date is NOT empty'); console.log(dateInput.value); > >);

We added a click event listener to a button element, so a function is invoked every time the button is clicked.

Inside the function, we selected the input element with a type of date .

The value property in the input can be used to set or get the selected date.

If the user hasn’t selected a date, the value will be empty.

Most commonly an empty value is represented by an empty string, but how different browsers implement this may vary.

Here are some examples of using the logical NOT (!) operator.

Copied!
console.log(!true); // 👉️ false console.log(!false); // 👉️ true console.log(!'hello'); // 👉️ false console.log(!''); // 👉️ true console.log(!null); // 👉️ true

You can imagine that the logical NOT (!) operator first converts the value to a boolean and then flips it.

Falsy values are: null , undefined , empty string, NaN , 0 and false .

This way we can be sure that we’ve covered all of the potential falsy values that an empty input type=»date» may have.

If I open my browser and click on the button without selecting a date, I can see that the empty input string gets logged to the console.

input date empty

If I now select a date in the input element and click on the button again, I get the message that the input is NOT empty and the selected date, formatted as YYYY-MM-DD .

input date not empty

# Checking if an input type=»date» is NOT empty

If you need to check if the input type=»date» is NOT empty, you can remove the logical NOT (!) operator.

Copied!
const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() const dateInput = document.getElementById('date'); if (dateInput.value) console.log('Input type date is NOT empty'); console.log(dateInput.value); > else console.log('Input type date is empty'); > >);

Now our if statement checks if the date input has a value.

If the input stores a value, the value will be a string formatted as YYYY-MM-DD , which is truthy, so the if statement will run.

Otherwise, if the input is empty, the else block runs.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью