Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

javascript - I need to restrict age for below 18 years age from the current date in Php

I need to restrict age for below 18 years of age from the current date in Php using javascript or ajax. How can I do this?

Please check my code I want to calculate the age onblur or onSubmit Please go through the code.

function getAge(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;
  }
  return age;
}
var age = getAge("1987/08/31");
alert(age);
if (age < 18) {
  alert("This age is restrict");

} else {

  alert("This age is allowed");
}
<form>
  <input type="text" id="dob" onBlur="function getAge(dateString)" />
</form>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this..

 <script>
function getAge() {
var dateString = document.getElementById("date").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 < 18 || age > 100)
{
alert("Age "+age+" is restrict");

} else {

alert("Age "+age+" is allowed");
}
} else {
alert("please provide your date of birth");
}
}


</script>
<input type="text" id="date" value="1987/08/31" onblur="getAge()">

http://js.do/code/65643


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...