jQuery 和验证插件中的日期验证之前

Before Date Validation in jQuery and validation plugin

我正在尝试验证 HTML 表单中输入的日期是否早于特定日期(1980 年 1 月 1 日),但我无法使用 jQuery 进行验证。这是我的代码:

jQuery.validator.addMethod("dateBeforeCheck",
    function (value, element) {
        var check = false;
        var datePattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;

        if (datePattern.test(value)) {
            var adata = value.split('/');
            var dd = parseInt(adata[1], 10);
            var mm = parseInt(adata[0], 10);
            var yyyy = parseInt(adata[2], 10);
            var xdata = new Date(yyyy, mm, dd);

            if (xdata.getFullYear() >= 1980) {
                check = true;
            }
            else {
                check = false;
            }
        }

        else {
            check = false;

        }

        return this.optional(element) || check;

    },
    "Date must be before January 1st, 1980"
);

HTML

<div class="form-group col-md-4">
  <label for="dateBefore">Date Before 01-01-1980</label>
  <input type="date" class="form-control" id="dateBefore" name="dateBefore">
</div>

关于什么可能导致它不起作用的任何想法?

检查这个

var $form = $("form"),
  $successMsg = $(".alert");

$.validator.addMethod("letters", function(value, element) {
var datePattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;

    if (datePattern.test(value)) {
       var fullDate = new Date(value);
       var minDate = new Date('01-01-1980');  
       return (fullDate>minDate);
    }
    else{
      return false;
    }

  
}, 'Date must be before January 1st, 1980');
$form.validate({
  rules: {
    date: {
      required: true,      
      letters: true
    }
  }
});
.alert {
  display: none;
}

.error {
  color: #e74c3c;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>


<form role="form">        
  <input type="text" class="form-control" name="date">
</form>

您的验证器可以从字符串创建两个日期对象并比较它们:

$.validator.addMethod("dateBeforeCheck",
    function (value, element) {
        var d = new Date(value);

        r = ( d < new Date('1980-01-01') );
        console.log(r) // For testing
        return r;
    },
    "Date must be before January 1st, 1980"
);

$('form').validate({
  rules: {
    dateBefore: {
      required: true,      
      dateBeforeCheck: true
    }
  }
})
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>

<form>
<div class="form-group col-md-4">
  <label for="dateBefore">Date Before 01-01-1980</label>
  <input type="date" class="form-control" id="dateBefore" name="dateBefore">
</div>
<button type="submit">
    Submit
</form>