javascript - jQuery.validation add 生日年龄验证时出现方法错误

标签 javascript jquery

我正在使用 jQuery.validation gem,当控制台中的年龄超过 18 岁时,我会出现未知的代码部分。您可以提交表单,但输入正确值后错误消息不会动态消失。我认为这是我的消息显示方式的一个直接错误,但我无法弄清楚。

控制台亮点

  • From the jQuery Validation Plugin v1.13.1 "result = $.validator.methods[ method ].call( this, val, element, rule.parameters );"

profiles.js

  $(document).ready(function () {
  {{$('#new_profile').validate({
  rules: {
 'profile[first_name]': {
   required: true,
   minlength: 2
 },
 'profile[last_name]': {
   required: true,
   minlength: 2
 },
  'profile[location]': {
    required: true,
    minlength: 2
  },
'profile[birthday]': {
    check_date_of_birth: true,
    require: true
  },
  'profile[operating_system]': {
    minlength: 1
  },
  'profile[about_me]': {
    required: true,
    minlength: 5,
    maxlength: 500
  }
}
   })
});

$.validator.addMethod("check_date_of_birth", function(value, element) {

var birthday = $("#profile_birthday").val();
var birthdaydate = Date.parse(birthday);
var difference = Date.now() - birthdaydate;
var ageYear = new Date(difference);
var age = Math.abs(ageYear.getUTCFullYear() - 1970);
return age > 18;
}, "You must be at least 18 years of age.");

个人资料表单

<div class="form_input">
<%= f.label(:birthday, "Date of Birth:") %>
<%= f.date_field(:birthday) %>
<label id="errorBirthday"></label>

最佳答案

我们需要扩展插件来创建自定义验证方法,以使用出生数据检查最低年龄:

<input type="date" name="dob" placeholder="mm/dd/yyyy"/>

$(document).ready(function() {

  $.validator.addMethod("minAge", function(value, element, min) {
    var today = new Date();
    var birthDate = new Date(value);
    var age = today.getFullYear() - birthDate.getFullYear();

    if (age > min + 1) {
      return true;
    }

    var m = today.getMonth() - birthDate.getMonth();

    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
      age--;
    }

    return age >= min;
  }, "You are not old enough!");

  $("form").validate({
    rules: {
      dob: {
        required: true,
        minAge: 18
      }
    },
    messages: {
      dob: {
        required: "Please enter you date of birth.",
        minAge: "You must be at least 18 years old!"
      }
    }
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>

<form>
  <input type="date" name="dob" placeholder="mm/dd/yyyy" />
  <br><br>
  <input type="submit" value="Submit">
</form>

关于javascript - jQuery.validation add 生日年龄验证时出现方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36026541/

相关文章:

javascript 从多个元素中检索类名

javascript - 正则表达式删除用加号替换所有空格和逗号

javascript - $http 调用挂起

javascript - 将具有相同属性的对象数组转换为具有数组值的一个对象

javascript - CodeIgniter Gmaps 获取标记对象经纬度

javascript - 点击事件对象跟踪问题

javascript - 从字符串中替换所有出现的 html 标记和特殊 unicode 字符

javascript - sapui5 中的必填字段验证器

javascript - 程序没有在提交表单时将用户输入记录到控制台?

javascript - 重写伪元素水平。垂直