Подсчет возраста и проверка правильности значений - PullRequest
1 голос
/ 28 сентября 2019

Мне нужно сделать страницу HTML, используя форму HTML и JavaScript, в котором человек вводит дату своего рождения в форме dd.mm.yyyy.Когда человек нажимает кнопку «Проверить», программа рассчитывает его возраст и печатает его как год (например, 32).(Округление до ближайшего года, вверх или назад).

Правила таковы: поле ввода не может быть пустым;он должен включать только цифры;длина значения должна быть правильной;дд должен быть между 1-31;mm между 1-12 и yyyy между 1900 и 2019.

Вот мой код до сих пор, и он не работает (я не получил еще далеко).Как я могу улучшить это?

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
    <title>Check your age</title>
</head>

<style>


</style>

<script>

 function check(){
  let data = "dd/mm/yyyy";
  let x = data.split("/");

 if(x.value == "" || x.value == null || isNaN(data) || dd < 1 || dd > 31 || mm < 1 || mm > 12 || yyyy < 1900 || yyyy > 2019){

 alert("Give a proper birth day!");
 return false;

 }
 return true;
 }


</script>

<body>

    <form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
        <Date of birth : <input type="text" value="" id="dateofbirth" name="time" onclick="check()"/>


    </form>
      <button onclick="check();">Check the age</button>


</body>

</html>

Ответы [ 2 ]

1 голос
/ 28 сентября 2019

Вы можете использовать ввод даты, чтобы получить дату от пользователя.Получив значение, вы можете сравнить разницу в годах и месяцах с сегодняшней датой.

var dob = document.getElementById('dateofbirth');

function check() {
  var today = new Date();
  var birthDate = new Date(dob.value);
  var y = today.getFullYear() - birthDate.getFullYear();
  var m = today.getMonth() - birthDate.getMonth();
  console.log(`${y} years and ${m} months`);
}
Date of birth : <input type="date" value="" id="dateofbirth" name="time" />
<button onclick="check();">Check the age</button>
0 голосов
/ 28 сентября 2019

я сделал один из них раньше.Вот код, который является функциональным и показывает возраст в годах, месяцах и днях.он приветствует вас как Иисуса, если вы вводите все нули, поэтому, если это кого-то «оскорбляет», вы можете захотеть убрать это - не стесняйтесь использовать

<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css?family=Acme" rel="stylesheet"> 
<meta charset="utf-8" />
<title>Age Calculator</title>
</head>
<body>


<style>
body {
  background-image: url('cake.jpg');
  background-repeat: no-repeat;
  background-size: 100%;
}
h1 {
  font-family: 'Acme', sans-serif;
}
</style>


<script>
//document.body.style.backgroundImage = "url('../images/cake.jpg')";
//document.getElementById("myDiv").style.backgroundImage = "url('images/cake.jpg')";  
let birthYear = prompt("Enter Your Birth Year");
let birthMonth = prompt("Enter Your Birth Month (As A Number)");
let birthDay = prompt("Enter Your Birth Day");
let date = new Date();
let currentYear = date.getFullYear();
let currentMonth = date.getMonth() + 1;
let currentDay = date.getDate();
let yearAge = currentYear - birthYear;
let monthAge = currentMonth - birthMonth;
let dayAge = currentDay - birthDay;
let monthPluralizer = "";
let dayPluralizer = "";
if (monthAge === 1) {
  monthPluralizer = "Month";
} else {
  monthPluralizer = "Months";
}
if (dayAge === 1) {
  dayPluralizer = "Day";
} else {
  dayPluralizer = "Days";
}
if (currentMonth < birthMonth) {
  monthAge = monthAge + 12;
  yearAge = yearAge - 1;
}
if (currentDay < birthDay) {
  monthAge = monthAge - 1;
  if (currentMonth === 1 || 3 || 5 || 7 || 8 || 10 || 12) {
    dayAge = dayAge + 31;
  } else if (currentMonth === 4 || 6 || 9 || 11) {
    dayAge = dayAge + 30;
  } else if (currentMonth === 2) {
    dayAge = dayAge + 28;
  }
}
if (currentMonth == birthMonth && currentDay < birthDay) {
  monthAge = monthAge + 12;
  yearAge = yearAge - 1;
}
document.write("<h1><p>Your Birth Date Is " + birthMonth + "/" + birthDay + "/" + birthYear + "</p></h1><br>");
document.write("<h1><p>Today's Date Is " + currentMonth + "/" + currentDay + "/" + currentYear + "</p></h1><br>");
document.write("<h1><p>You Are " + yearAge + " Years, " + monthAge + " " + monthPluralizer + " & " + dayAge +
  " " + dayPluralizer + " Old.</p></h1><br>");
if (birthMonth == 0 && birthDay == 0 && birthYear == 0 ) {
  document.write("<h1><p>Hello Jesus!<p></h1>")
} else if (birthMonth === null && birthDay === null && birthYear === null ) {
  document.write("<h1><p>Hello Jesus!<p></h1>")
}
</script>

</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...