I'm using a datetimepicker plugin that I found here which works quite well.
The only problem now is that it breaks the standard date validation included with the jquery validation plugin because of the added time on the end of the string in the input box.
Here is what I have so far in a demo. I added a validation method that checks if the value is a date, but it doesn't accept the time.
I need help with writing the custom validation method. How do I split the date
and time
string and then perform the tests to validate them?
Thanks
Below jQuery code shows exactly the same thing. $(function() { $('#btnSubmit'). bind('click', function(){ var txtVal = $('#txtDate'). val(); if(isDate(txtVal)) alert('Valid Date'); else alert('Invalid Date'); }); });
val(); var endDate = $('#end_date'). val(); if (endDate < startDate){ alert('End date should be greater than Start date. '); $('#end_date'). val(''); } });
You can use the datepicker. getDate() method to get the currently selected date object from the input field.
You already have validation for the date
rule. Otherwise, you can look inside the jQuery Validate plugin to obtain that:
date: function( value, element ) {
return this.optional(element) || !/Invalid|NaN/.test(new Date(value).toString());
},
Here is a custom method I found for validating the time
portion of your string.
$.validator.addMethod("time", function (value, element) {
return this.optional(element) || /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(value);
}, "Please enter a valid time.");
Time Demo: http://jsfiddle.net/9CdvN/
Simply combine the two functions into your "DateTime" method. Then split your input value at the space and test each part accordingly.
Here's a demo where I've combined the Date & Time methods together. It accepts the following format, yyyy/mm/dd hh:mm
, so you'll simply need to tweak it a bit.
http://jsfiddle.net/9CdvN/2/
The datetime picker you mentioned says it uses jQuery UI's datepicker widget. You can control the format of the date you receive from the widget using the ui datepicker API, specifically the dateFormat method.
You should be able to set the datepicker up to supply a date in the format that you need for your validation.
Hope that helps!
Might I suggest you switch plugins? http://www.datejs.com/ has an outstanding number of ways to validate dates and some ridiculous syntactic sugar:
// Convert text into Date
Date.parse('today');
Date.parse('t + 5 d'); // today + 5 days
Date.parse('next thursday');
Date.parse('February 20th 1973');
Date.parse('Thu, 1 July 2004 22:30:00');
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