如何组织这个功能才能正常工作?

时间:2012-06-21 05:29:39

标签: javascript jquery validation date

我正在努力扩展我的插件Ideal Forms中的日期过滤器,以允许用户配置日期格式,即dd/mm/yyyymm-dd-yyyy ...这就是我得到的到目前为止:

  date: {
    regex: function (input, value) {
      var

      // Just grabbing some info from the plugin...
      data = input.userOptions.data
        ? input.userOptions.data.date
        : { format: 'mm/dd/yyyy' }, // default format

      separator = '\\' + /[^mdy]/.exec(data.format)[0], // extract separator
      userFormat = data.format.replace(/[^mdy]/g, ''), // convert to proper format

      isDate = function (m, d, y) {
        return m > 0 &&
          m < 13 &&
          y > 0 &&
          y < 32768 &&
          d > 0 &&
          d <= (new Date(y, m, 0)).getDate()
      },

      n2 = '(\\d{1,2})', // day and month
      n4 = '(\\d{4})', // year

      format = {
        'mmddyyyy': function () {
          var re = new RegExp(n2 + separator + n2 + separator + n4),
              m = re.exec(value)
          return m && isDate(m[1], m[2], m[3])
        },
        'ddmmyyyy': function () {
          var re = new RegExp(n2 + separator + n2 + separator + n4),
              m = re.exec(value)
          return m && isDate(m[2], m[1], m[3])
        },
        'yyyymmdd': function () {
          var re = new RegExp(n4 + separator + n2 + separator + n2),
              m = re.exec(value)
          return m && isDate(m[2], m[3], m[1])
        },
        'yyyyddmm': function () {
          var re = new RegExp(n4 + separator + n2 + separator + n2),
              m = re.exec(value)
          return m && isDate(m[3], m[2], m[1])
        }
      }

      return format[userFormat]() || format['mmddyyyy']()
    },

当使用其他格式时,由于函数mm/dd/yyyy测试以月值开头的日期,因此会出现默认isDate问题,因此当我传递自定义格式dd-mm-yyyy时,调用isDate(m[2], m[1], m[3])有效,但它也会验证12-13-1986但不是13-13-1986等值。

我该如何开始修复此问题?有什么想法吗?

1 个答案:

答案 0 :(得分:1)

修改

我也想谈谈你对isDate的回归的评论。该函数表现如预期,问题出在其他地方。我没有足够的解剖你的代码来说明错误的位置,但isDate是正确的:http://jsfiddle.net/nQMYe/


原始答案

我对这里的片段变体表示祝你好运:http://joey.mazzarelli.com/2008/11/25/easy-date-parsing-with-javascript/

基本上,它在Date对象中实现了fromString方法。我并不关心这种方法,因此我将我的实现修改为独立的函数,并消除了一些不必要的内容。也就是说,它很有效。

基本思想是首先规​​范化输入。由于您永远不知道用户是否为您提供了1.11.20113~12~2012等格式,因此首先要删除这些噪音:

data = data.replace(/[^:a-z0-9]/g, '-');

我们丢弃所有非字母数字字符并放入-,您似乎更喜欢/ - 无论如何,只需获得输入一致性。我们保留alpha,以便我们也可以处理March 18, 2012

然后,片段解析输入,提取时间(如果给,使用:识别),然后它建立一年。正如评论中所指出的那样,日期和月份以大多数合理的格式彼此相邻,因此您需要确定什么不是年份并且从那里开始。然后是确定月份,然后是当天的消除过程。

不是我的代码,所以我并不是要赞美这个想法,但同样,这件事就像宣传的一样。您既可以按原样使用它(BSD许可证),也可以通过源阅读并剖析概念。

以下是代码,供后人使用:

/**
 * @author Joey Mazzarelli
 * @website http://bitbucket.org/mazzarelli/js-date/
 * @website http://joey.mazzarelli.com/2008/11/25/easy-date-parsing-with-javascript/
 * @copyright Joey Mazzarelli
 * @license BSD license
 */

Date.fromString = (function () {

  var defaults = {
    order : 'MDY',
    strict : false
  };

  var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG",
      "SEP", "OCT", "NOV", "DEC"];

  var abs = ["AM", "PM", "AFTERNOON", "MORNING"];

  var mark = function (str, val) {
    var lval = val.toLowerCase();
    var regex = new RegExp('^' + lval + '|(.*[^:alpha:])' + lval, 'g');
    return str.replace(regex, '$1' + val);
  };

  var normalize = function (str) {
    str = str.toLowerCase();
    str = str.replace(/[^:a-z0-9]/g, '-');
    for (var i=0; i<months.length; i++) str = mark(str, months[i]);
    for (var i=0; i<abs.length; i++) str = mark(str, abs[i]);
    str = str.replace(/[a-z]/g, '');
    str = str.replace(/([0-9])([A-Z])/g, '$1-$2');
    str = ('-' + str + '-').replace(/-+/g, '-');
    return str;
  };

  var find_time = function (norm) {
    var obj = {date:norm, time:''};
    obj.time = norm.replace(
        /^.*-(\d\d?(:\d\d){1,2}(:\d\d\d)?(-(AM|PM))?)-.*$/, '$1');
    if (obj.time == obj.date)
      obj.time = norm.replace(/^.*-(\d\d?-(AM|PM))-.*$/, '$1');
    if (obj.time == obj.date) obj.time = '';
    obj.date = norm.replace(obj.time, '');
    obj.time = ('-' + obj.time + '-').replace(/-+/g, '-');
    obj.date = ('-' + obj.date + '-').replace(/-+/g, '-');
    return obj;
  };

  var find_year = function (norm) {
    var year = null;

    // Check for a 4-digit year
    year = norm.replace(/^.*-(\d\d\d\d)-.*$/, '$1');
    if (year != norm) return year; else year = null;

    // Check for a 2-digit year, over 32.
    year = norm.replace(/^.*-((3[2-9])|([4-9][0-9]))-.*$/, '$1');
    if (year != norm) return year; else year = null;

    // Day is always by month, so check for explicit months in 
    // first or third spot
    year = norm.replace(/^.*-[A-Z]{3}-\d\d?-(\d\d?)-.*$/, '$1');
    if (year != norm) return year; else year = null;
    year = norm.replace(/^.*-(\d\d?)-\d\d?-[A-Z]{3}-.*$/, '$1');
    if (year != norm) return year; else year = null;

    // If all else fails, use the setting for the position of the year.
    var pos = '$3';
    if (defaults.opts.order.charAt(0) == 'Y') pos = '$1';
    else if (defaults.opts.order.charAt(1) == 'Y') pos = '$2';
    year = norm.replace(/^.*-(\d\d?)-([A-Z]{3}|\d{1,2})-(\d\d?)-.*$/, pos);
    if (year != norm) return year; else year = null;

    return year;
  };

  var find_month = function (norm, year) {
    // Check for an explicity month
    var matches = norm.match(/[A-Z]{3}/);
    if (matches && matches.length) return matches[0];

    // Remove the year, and unless obviously wrong, use order
    // to chose which one to use for month.
    var parts = norm.replace(year + '-', '').split('-');
    if (parts.length != 4) return null;
    var order = defaults.opts.order;
    var md = order.indexOf('M') < order.indexOf('D')? 1: 2;
    return (parseInt(parts[md], 10) <= 12)? parts[md]: parts[md==1? 2: 1];
  };

  var find_day  = function (norm, year, month) {
    return norm.replace(year, '').replace(month, '').replace(/-/g, '');
  };

  var create_absolute = function (obj) {

    var time = obj.time.replace(/[-APM]/g, '');
    var parts = time.split(':');
    parts[1] = parts[1] || 0;
    parts[2] = parts[2] || 0;
    parts[3] = parts[3] || 0;
    var ihr = parseInt(parts[0], 10);
    if (obj.time.match(/-AM-/) && ihr == 12) parts[0] = 0;
    else if (obj.time.match(/-PM-/) && ihr < 12) parts[0] = ihr + 12;
    parts[0] = ("0" + parts[0]).substring(("0" + parts[0]).length - 2);
    parts[1] = ("0" + parts[1]).substring(("0" + parts[1]).length - 2);
    parts[2] = ("0" + parts[2]).substring(("0" + parts[2]).length - 2);
    time = parts[0] + ":" + parts[1] + ":" + parts[2];
    var millisecs = parts[3];

    var strict = defaults.opts.strict;
    if (!obj.year && !strict) obj.year = (new Date()).getFullYear();
    var year = parseInt(obj.year, 10);
    if (year < 100) {
      year += (year<70? 2000: 1900);
    }

    if (!obj.month && !strict) obj.month = (new Date()).getMonth() + 1;
    var month = String(obj.month);
    if (month.match(/[A-Z]{3}/)) {
      month = "JAN-FEB-MAR-APR-MAY-JUN-JUL-AUG-SEP-OCT-NOV-DEC-"
          .indexOf(month) / 4 + 1;
    }
    month = ("0" + month).substring(("0" + month).length - 2);
    if (!obj.day && !strict) obj.day = (new Date()).getDate();
    var day = ("0" + obj.day).substring(("0" + obj.day).length - 2);

    var date = new Date();
    date.setTime(Date.parse(year + '/' + month + '/' + day + ' ' + time));
    date.setMilliseconds(millisecs);
    return date;
  };

  var parse = function (norm) {
    return absolute(norm);
  };

  var absolute = function (norm) {
    var obj = find_time(norm);
    obj.norm = norm;
    obj.year = find_year(obj.date);
    obj.month = find_month(obj.date, obj.year);
    obj.day = find_day(obj.date, obj.year, obj.month);
    return create_absolute(obj);
  };

  return function (fuzz, opts) {
    defaults.opts = { order: defaults.order, strict: defaults.strict };
    if (opts && opts.order) defaults.opts.order = opts.order;
    if (opts && opts.strict != undefined) defaults.opts.strict = opts.strict;
    var date = parse(normalize(fuzz));
    return date;
  };

})();