年龄验证 Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15738782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:54:50  来源:igfitidea点击:

Age Validation Javascript

javascriptvalidation

提问by arvee amor

Have this so far but wont work?

到目前为止,但不会工作?

//if no age was entered it will allow
var age=document.getElementById('age1').value;
if(age == "")     
    return true;

//check if age is a number or less than or greater than 100
if (isNaN(age)||age<1||age>100)
{ 
    alert("The age must be a number between 1 and 100");
    return false;
}

I just need to validate!!!!

我只需要验证!!!!

回答by Rohit Vyas

Why don't you use the regular expression to validate this. Use below regular expression for this:

为什么不使用正则表达式来验证这一点。为此使用以下正则表达式:

/^[1-9]?[0-9]{1}$|^100$/

This regex which matches a number of 1 or 2 digits, or 100:

此正则表达式匹配 1 位或 2 位数字或 100:

回答by rab

try shortcut +to convert into Number, or use parseInt(value, 10)

尝试快捷方式+转换为Number,或使用parseInt(value, 10)

var age = +document.getElementById('age1').value;

if ( !( age > 1 && age<100 ) ){

        alert("The age must be a number between 1 and 100");
        return false;
}

return true;

回答by Rob G

You'll want to parseInt() the value you get back into age, since it comes in as a string.

你会想要 parseInt() 你回到年龄的值,因为它是作为一个字符串出现的。

回答by Tanzeel Kazi

You should convert your string to a number using parseInt(value, radix). It's a good practice to provide the radixwhen using this method. In your case it is a decimal so the radixis 10.

您应该使用 将字符串转换为数字parseInt(value, radix)radix使用此方法时提供 是一个很好的做法。在你的情况下,它是一个小数,所以radix10.

Try this:

试试这个:

//if no age was entered it will allow
var age=document.getElementById('age1').value;
if(age === "") {
  return true;
}

// convert age to a number
age = parseInt(age, 10);

//check if age is a number or less than or greater than 100
if (isNaN(age) || age < 1 || age > 100)
{ 
  alert("The age must be a number between 1 and 100");
  return false;
}

回答by IshaniNet

Try this

试试这个

<input type='text' name='dob' onblur="Age_validator(this.value)" style='width:108px;' />
<div><span id="dob1"></span></div>
function Age_validator(str){
    // which user inputs
    str = str.split("-");
    var dd = str[0];
    var mm = str[1];
    var yy = str[2];
    // Current date calculation
    var d = new Date();
    var ds = d.getDate();
    var ms = d.getMonth();
    var ys = d.getFullYear();
    // convert 18years as days from current date
    var days = ((18 * 12) * 30) + (ms * 30) + ds;
    // convert days from input value
    var age = (((ys - yy) * 12) * 30) + ((12 - mm) * 30) + parseInt(30 - dd);

    if((days - age) <= '0'){
        console.log((days - age));
        document.getElementById('dob1').innerHTML = 'Valid';
        // or return your own script
    }else{
        console.log((days - age));
        document.getElementById('dob1').innerHTML = 'Invalid';
        // or return your own script
    }
}

Please +1 if it useful

如果有用请+1

回答by Fernando Palma

Try this works form me :)

试试这个对我有用:)

var dateString = document.getElementById("age1").value;
if(dateString !=""){
  var today = new Date();
  var birthDate = new Date(dateString);
  var age = today.getFullYear() - birthDate.getFullYear();
  var m = today.getMonth() - birthDate.getMonth();
  var da = today.getDate() - birthDate.getDate();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  if(m<0){
    m +=12;
  }
  if(da<0){
    da +=30;
  }
  if (age >= 1 && age <= 99) {
    return true;
  }else {
    return false;
  }

}else {
  return false;
}

Also you can use other libraries to calculate time like moment https://momentjs.com/that can make easier time calculations (seconds, minutes, hours, days, years, etc...)

您也可以使用其他库来计算时间,例如 moment https://momentjs.com/,可以更轻松地计算时间(秒、分钟、小时、天、年等...)

回答by Musa Baloyi

Try this, minimum age of 18 and a maximum of 70

试试这个,最低 18 岁,最高 70 岁

validateAge(year,month,day) {

    const max_year = new Date().getFullYear() - 70 ;
    const min_year = new Date().getFullYear() - 18 ;
    const _month = new Date().getMonth() + 1;
    const _day = new Date().getDay();

    const dateofbirthDate = new Date(year + "-"+month+"-"+day);
    const mindate = new Date( min_year+ '-'+_month+'-'+_day);
    const maxdate = new Date(max_year+ '-'+_month+'-'+_day);


    if(dateofbirthDate <= mindate && dateofbirthDate >= maxdate){
        return true;
    }
    else
        return false; 
}