如何根据 3 个单独的输入使用 Javascript 检查用户的年龄 [英] How to check user's age with Javascript based on 3 seperate inputs

查看:22
本文介绍了如何根据 3 个单独的输入使用 Javascript 检查用户的年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 个单独的输入,一个用于日、月和年.页面加载时只需要显示年份,用户只需先填写年份即可.

目前我可以通过简单的检查年份来检查某人是否超过 16 岁或未满 16 岁.

checkAge() {让 yearOfBirth = new Date().getFullYear() - this.form.dobYear;如果 (yearOfBirth > 16) {this.isSixteen = false;this.belowSixteen = false;}}

当比较当前年份减去用户输入时,如果等于16,那么我有两个select元素显示日和月,这两个都需要填写.

这里我需要比较用户输入的年龄是否确实是 16 岁,如果他们离 16 岁生日还有几个月的时间,那么我希望他们被视为低于 16 岁,否则将他们显示为 16 岁年龄.

如果有帮助,我也在使用 BootstrapVue 和 Vue.js.

解决方案

只查看年份:

function calculateYearDiff(y){//生日年份返回 (new Date()).getUTCFullYear() - y;}

^这将返回现在和给定年份之间的年份差异.

要查看完整的生日日期:

function calculateAge(y,m,d){//生日年月日var 生日 = 新日期(y + '-' + m + '-' + d);var ageDifMs = Date.now() -birthday.getTime();var ageDate = 新日期(ageDifMs);返回 Math.abs(ageDate.getUTCFullYear() - 1970);}

^这将返回给定生日和现在之间的整年.

I have 3 seperate inputs, one for day, month and year. Only the year is required to show on page load, the user only needs to fill in the year first.

Currently I am able to check if someone is over 16 or under 16 by simply checking the year.

checkAge() {
    let yearOfBirth = new Date().getFullYear() - this.form.dobYear;

    if (yearOfBirth > 16) {
      this.isSixteen = false;
      this.belowSixteen = false;
    }
}

When comparing the current year minus the user's input, if it equals to 16, then I have two select elements displaying the day and month, both of these will need to be filled in.

Here I need to compare the users input to see if the age is indeed 16, if they are a few months away from there 16th birthday for example then I want them to be seen as below 16, otherwise show them as 16 years of age.

I am using BootstrapVue and Vue.js also if it helps.

解决方案

To check only the year:

function calculateYearDiff(y){ // birthday year
   return (new Date()).getUTCFullYear() - y;
}

^This will return difference in years between now and given year.

To check full birthday date:

function calculateAge(y,m,d){ // birthday year, month, day
   var birthday = new Date(y + '-' + m + '-' + d);
   var ageDifMs = Date.now() - birthday.getTime();
   var ageDate = new Date(ageDifMs);
   return Math.abs(ageDate.getUTCFullYear() - 1970);
}

^This will return full years between given birthday and now.

这篇关于如何根据 3 个单独的输入使用 Javascript 检查用户的年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆