Full year validation jQuery datepicker dpDate

I am using jQuery datepicker and the dpDate plugin to validate the input. I want the validation to fail when the year is not in 4 digits. (when someone enters the date using keyboard this seems to be possible).

dpDate returns true on 80-01-01 (Jan 1, 1980). But it should users force to write it like 1980-01-01

Can anyone help me?

1 Answer

The name of the plugin is jquery.ui.datepicker.validation.js; dpDate is one of the new validation methods it defines. For the benefit of other readers, it can be found at:

This method simply uses $.datepicker.parseDate using the dateFormat you specified -- if it doesn't report an error, it considers the input valid. Since parseDate allows abbreviated years, so does the plugin.

Instead, you can use the regular expression /^\d{4}-\d{2}-\d{2}$/; this question shows how to add a regex validation method. If you combine it with the dpDate method, it will check that it has 4 digits and that it's also a valid date.

jQuery validate: How to add a rule for regular expression validation?

What I do in my application is a little different. I simply don't allow the user to edit the date field directly. I set it readonly, but this still allows the datepicker to fill it in. Since the datepicker always enters 4-digit years, I don't have to worry much about validating it.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like