当用户使用javascript和thymelaf在注册表中输入她的出生日期时,如何自动计算年龄



我想在用户在登记表中输入了她的出生日期。我正在使用ThymelafJavaScritpt for Frontend,但我无法计算年龄当用户输入她的出生日期时自动。我生成注册字段是动态的,但我不知道如何计算年龄。我是新来的。这是我的密码SignUpForm.html

<div class="singup-form">
<form id="form_signup">
<input id="id" th:field="*{id}" type="hidden"/>
<div th:each="item,iterStat : *{form}" >
<!--                        <label th:label="${str.getLabel()}" th:type="${str.getType()}" th:text="${str.value}" ></label>-->
<div class="form-group">
<label th:for="${item.name}" th:text="${item.label}"></label>
<div th:if="${item.validation == 'dob'}" >
<input class="form-control" th:id="${item.name}" th:name="${item.name}" th:placeholder="${item.placeholder}" th:required="${item.required}"
th:type="${item.type}" th:attr="max=${#dates.format(#dates.createNow(), 'MM-dd-yyyy')}" />
</div>
<div th:unless="${item.validation == 'dob'}" >
<input class="form-control" th:id="${item.name}" th:name="${item.name}" th:placeholder="${item.placeholder}" th:required="${item.required}"
th:type="${item.type}"/>
</div>
</div>
</div>

广告.kt

class Advertisement(
val form:ArrayList<Form>?=null,
)
class Form(
val type:String="",
val required:Boolean,
val label:String="",
val placeholder:String="",
val name:String="",
val value:String="",
val validation:String="",
val min:Int,
)

SignUp.kt

package com.ape.model
data class SignUp(
val id:Int,
val email:String?="",
val login_type:String?="",
val dob:String?=""
)
data class ModelSignUp(
val firstname:String?="",
val month:String?="",
val day:String?="",
val year:String?="",
val email:String?="",
val phone_number:String?="",
)

Signup.html

<script type="text/javascript">
var minAge = 18;
function _calcAge() {
var date = new Date(document.getElementById("date").value);
var today = new Date();
var timeDiff = Math.abs(today.getTime() - date.getTime());
var age1 = Math.ceil(timeDiff / (1000 * 3600 * 24)) / 365;
return age1;
}
//Compares calculated age with minimum age and acts according to rules//
function _setAge() {
var age = _calcAge();
//alert("my age is " + age);
if (age < minAge) {
alert("You are not allowed into the site. The minimum age is 18!");
} else
alert("Welcome to my Site");
window.open(main.htm, _self);
}

</script>

我无法计算用户年龄我该如何计算用户年龄我如何计算年龄

下面是一个使用moment.js 进行日期比较的简单示例

该图书馆将进行精确的计算,会计闰年等…

document.querySelector("#birth").addEventListener("change", function(){
// That is today minus 18 years
let criteria_date = moment().subtract(18, "years");

// Taht is the submitted date
let birth = moment(this.value)

// The birth date should be less than the criteria_date
if(birth > criteria_date){
alert("Bye kid!")
} else{
alert("Welcome")
// Redirect to your app...
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Enter your birth date: <input type="date" id="birth">

最新更新