【问题标题】:how to validate Date of birth with three textbox of date month year by jquery validator如何通过jquery验证器使用日期月年的三个文本框来验证出生日期
【发布时间】:2012-11-17 04:56:11
【问题描述】:

我需要使用带有三个单独文本框的 jquery 验证器来验证出生日期。

如何做到这一点,请帮忙。

HTML 代码

<input type="text" maxlength="2" placeholder="DD" class="dob-day  fillone" name="dob-day" id="dob-day" data-fieldgroup="dob" data-fillone-field="true" />
<input type="text" maxlength="2" placeholder="MM" id="dob-month" class="dob-month fillone" data-fieldgroup="dob" data-fillone-field="true">
<input type="text" maxlength="4" placeholder="YYYY" class="dob-year fillone" id="dob-year" data-fieldgroup="dob" data-fillone-field="true">

我正在使用数据组对文本框进行分组

【问题讨论】:

    标签: javascript jquery-validate


    【解决方案1】:

    您应该为此创建一个自定义验证方法,并使用 validate 提供的 groups 选项:

    /* Custom validation method to validate a date based on several fields: */
    $.validator.addMethod("datemultiple", 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),
            dateEntered = new Date(year, month - 1, day);
    
        return this.optional(element) || !isNaN(dateEntered.valueOf());
    
    }, "Please enter a valid date");
    
    $(document).ready(function() {
        $("#myform").validate({
            groups: {
                /* Only display one validation message for day, month, and year: */
                dateOfBirth: "dob-day dob-month dob-year"
            },
            rules: {
                'dob-day': {
                    required: true,
                    datemultiple: ["#dob-day", "#dob-month", "#dob-year"]
                },
                'dob-month': {
                    required: true
                }
            },
            /* Place error messages after the "year" field */
            errorPlacement: function ($error, $element) {
                if ($element.data("fieldgroup") === "dob") {
                    $error.insertAfter("#dob-year");
                }
            }
        });
    });
    

    示例: http://jsfiddle.net/xHC86/

    【讨论】:

    • 如果您想“等待”所有 3 个输入都被填充然后验证怎么办?当然,您可以检查它们是否都已填充,然后进行验证。但这会在您实际提交时引起问题 - 通过按下提交按钮。
    • 在您的示例中,如果我填写一个字段,然后移至第二个字段 - 将显示错误消息。如果我想等待用户填写所有三个元素然后验证怎么办?这就像跨字段验证。
    【解决方案2】:

    我编写了一个 Javascript 模块来处理数据是否有效,您可以在 JSFiddle 链接中查看完整的工作示例。

    http://jsfiddle.net/dceast/vmHjN/

    这是进行验证的模块:

    var compareDate, checkDates = false;
    var validateObject = {
        init: function(year, month, day) {
            return this.compareDate.init(year, month, day);
        },
        compareDate: {
            init: function(year, month, day) {
                var isValid = false;
                // Compensate for zero based index, if month was not
                // subtracted from one 0 === Jan, 1 === Feb, 2 === Mar
                month -= 1;
    
                // Create a new date object with the selected
                // year, month, and day values and retrieve the
                // milliseconds from it.
                var mSeconds = (new Date(year, month, day)).getTime();
                var objDate = new Date();
    
                // Set the time of the object to the milliseconds 
                // retrieved from the original date. This will
                // convert it to a valid date.
                objDate.setTime(mSeconds);
    
                // Compare if the date has changed, if it has then
                // the date is not valid 
                if (objDate.getFullYear() === year &&
                    objDate.getMonth() === month &&
                    objDate.getDate() === day) 
                {
                    isValid = true;
                }
                return isValid;
            }
        }
    };
    

    【讨论】:

    • 这是一个很棒的代码,但如果你能在 jquery 验证器格式中更改它会很棒
    【解决方案3】:

    对不起,我不会说英语

    您可以分别检查日期

    我认为使用三个文本框很容易:( 只是js

    【讨论】:

      【解决方案4】:
      var compareDate, checkDates = false;
      var validateObject = {
          init: function(year, month, day) {
              return this.compareDate.init(year, month, day);
          },
          compareDate: {
              init: function(year, month, day) {
                  var isValid = false;
                  // Compensate for zero based index, if month was not
                  // subtracted from one 0 === Jan, 1 === Feb, 2 === Mar
                  month -= 1;
      
                  // Create a new date object with the selected
                  // year, month, and day values and retrieve the
                  // milliseconds from it.
                  var mSeconds = (new Date(year, month, day)).getTime();
                  var objDate = new Date();
      
                  // Set the time of the object to the milliseconds
                  // retrieved from the original date. This will
                  // convert it to a valid date.
                  objDate.setTime(mSeconds);
      
                  // Compare if the date has changed, if it has then
                  // the date is not valid
                  if (objDate.getFullYear() === year&&
                      objDate.getMonth() === month &&
                      objDate.getDate() === day)
                  {                
                      if(objDate <= new Date())
                      {
                          isValid = true;
                      }                   
                  }
                  return isValid;
              }
          }
      };
      
      $(function() {
          var validateButton = $('#btValidate');
      
          validateButton.click(function(e) {
              var month = parseInt(document.getElementById('month').value, 0),
                  day = parseInt(document.getElementById('day').value, 0),
                  year = parseInt(document.getElementById('year').value, 0),
                  alertBox = $('#alert'),
                  isValid = false;
      
              isValid = validateObject.init(year, month, day);
              var color, message;
      
              if (isValid === true)
              {
                  color = "#008000";
                  message = "Your date is valid!";
              }
              else if (isValid === false)
              {
                  color = "#F00";
                  message = "Your date is not valid!";
              }
              alertBox.css('background', "" + color)
                  .html("<p>"+ message +"</p>")
                  .stop()
                  .animate({
                      width: "200px",
                      paddingLeft: "75px"
                  }, 1750, "easeOutBounce", function() {
                      $(this).animate({
                          width: "0px",
                          paddingLeft: "0px"
                      }, 1000, "easeInBounce");
              });
          });
      });
      

      这里的工作代码: http://jsfiddle.net/vmHjN/140/

      【讨论】:

      • 请将代码直接粘贴到您的答案中,并提供一些关于代码如何帮助 OP 的说明。
      猜你喜欢
      • 2012-03-10
      • 2012-07-13
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      • 2013-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多