如何在3个字段中验证日期输入?

时间:2012-02-09 19:58:32

标签: javascript jquery-validate

我有3个日期输入字段:

<input type="text" id="passport-doi-1" name="passport-doi-1" placeholder="DD" maxlength="2">
<input type="text" id="passport-doi-2" name="passport-doi-2" placeholder="MM" maxlength="2">
<input type="text" id="passport-doi-3" name="passport-doi-3" placeholder="YYYY" maxlength="4">

如何使用jQuery Validate插件验证如果输入日期,那么这是正确的吗?

看起来我应该创建groups个字段(只有一条错误消息),然后是自定义验证规则。但它应该是什么样的?

UPD 即可。我试图做以下事情,但它不起作用:

$.validator.addMethod('validDate', function (value, element) {
  var dd = $("#passport-doi-dd").val();
  var mm = $("#passport-doi-mm").val();
  var yyyy = $("#passport-doi-yyyy").val();
  if (dd=="" && mm=="" && yyyy=="") return true;
  try {
    var date = new Date(yyyy,mm-1,dd,0,0,0,0);
    return mm===(date.getMonth()+1) && dd===date.getDate() && yyyy===date.getFullYear();
  }
  catch(er) {
    return false;
  }
}, 'Please use format DD MM YYYY.');

  ...
  rules: {
    "passport-doi-dd": {
      required: false,
      validDate: true,
      range: [1, 31]
    }, 
    "passport-doi-mm": {
      required: false,
      validDate: true,
      range: [1, 12]
    }, 
    "passport-doi-yyyy": {
      required: false,
      validDate: true,
      range: [1990, 2012]
    }
  },
  messages: {
    "passport-doi-dd": "Please use format DD MM YYYY.",
    "passport-doi-mm": "Please use format DD MM YYYY.",
    "passport-doi-yyyy": "Please use format DD MM YYYY."
  }

1 个答案:

答案 0 :(得分:2)

您走在正确的轨道上 - 您需要传递Date构造函数而不是字符串(val将返回字符串)。您还可以利用自定义规则的params参数使其更具可扩展性(不特定于具有特定id s的三个字段):

$.validator.addMethod("multidate", function (value, element, params) {
  var daySelector = params[0]
      , monthSelector = params[1]
      , yearSelector = params[2]
      , day = parseInt($(daySelector).val(), 10)
      , month = parseInt($(monthSelector).val(), 10)
      , year = parseInt($(yearSelector).val(), 10)
      , date = new Date(year, month, day);

  return (!$(daySelector).val() && !$(monthSelector).val() && !$(yearSelector).val()) || 
    !isNaN(date.getTime());

});


$(document).ready(function () {
  var dateFields = ["#passport-doi-1", "#passport-doi-2", "#passport-doi-3"];
  $("#dateform").validate({
    errorLabelContainer: "#errors",
    groups: {
      date: dateFields.join("")
    },
    rules: {
      "passport-doi-1": {
        multidate: dateFields
      },
      "passport-doi-2": {
        multidate: dateFields
      },
      "passport-doi-3": {
        multidate: dateFields
      }
    },
    messages: {
      "passport-doi-1": {
        multidate: "Please enter a valid date"
      },
      "passport-doi-2": {
        multidate: "Please enter a valid date"
      },
      "passport-doi-3": {
        multidate: "Please enter a valid date"
      }
    }
  });
});

认为 group选项仅用于分组错误消息(因此您仍需要为每个输入定义验证规则)。

示例: http://jsbin.com/oqawaz/9