Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery datepicker : Validate current input value?

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?

like image 644
user169867 Avatar asked Jun 30 '10 13:06

user169867


3 Answers

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>
like image 147
Humayoo Avatar answered Oct 23 '22 18:10

Humayoo


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) {}
like image 35
Alexander Avatar answered Oct 23 '22 19:10

Alexander


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.

like image 3
Eric Brenden Avatar answered Oct 23 '22 18:10

Eric Brenden