jquery validate add method to validate datetime

不打扰是莪最后的温柔 提交于 2019-12-20 20:59:07

问题


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


回答1:


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/




回答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!




回答3:


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');


来源:https://stackoverflow.com/questions/15787503/jquery-validate-add-method-to-validate-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!