I've been using the Datepicker plugin from jQuery UI. I want to be able to validate if the input textbox it is attached to currently has a valid date or not.
For example:
If someone decides to type in 02/30/2010
I'd like to be able to somehow ask the plugin if that current input value is a valid date (which it is not in this case).
Does anyone know how this can be done?
You can solve your problem by making text box read only and set date format as you like. So User is not able to type anything in text box, user only select correct date format(which you set) from date picker. Please see the below example.
<p>Date: <input type="text" id="datepicker" size="30" readonly="readonly"/></p>
<script>
$(function() {
$( "#datepicker" ).datepicker();
$( "#datepicker" ).datepicker( "option", "dateFormat",'yy-mm-dd');
});
</script>
It's very easy
let value = $(this).val();
let format = $(this).datepicker('option', 'dateFormat');
let valueIsValid = false;
try {
$.datepicker.parseDate(format, value);
valueIsValid = true;
}
catch (e) {}
Although this question is almost two years old, I have recently dealt with a similar solution and found that the Globalize library is the best approach. For example, suppose you have a textbox that has a jQueryUI datepicker attached to it. When focus is lost on the textbox, you can use Globalize to validate the entered date. In this case the textbox is blanked if the date is invalid or put in a standard format if the date is valid:
$('#myDateTextBox').blur(function () {
var parsedDate = Globalize.parseDate($(this).val());
if (parsedDate == null) {
$(this).val('');
}
else {
$(this).val(Globalize.format(parsedDate, 'd'));
}
The Globalize
library allows you to specify a culture (using the language of the request ideally) so the user can enter a date in the format for their culture.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With