Сравните две даты в Javascript из формы HTML - PullRequest
0 голосов
/ 07 ноября 2018

Я только начал изучать php, и время от времени мне нужны некоторые функции JS. Сегодня один из тех дней. У меня есть HTML-форма, где я спрашиваю возраст моих пользователей, и я хотел бы проверить, ставят ли они более точную или равную дату по сравнению с сегодняшней датой. Это HTML-код:

var borndate = document.getElementById("borndate");
var date = new Date()
	 
function comparedate(){
	if (borndate >= date.getFullYear()){
			alert("Looks like you are to young!");
                        return false;
	} else {
		return true;
	}
 }
<div class="form">
    	<form class="login-form" method="POST" action="main.php">
    		<input type="date" id="borndate" name="borndate" required="required"/>
                <input type="submit" value="submit" onclick="comparedate()"/>
    	</form>
    </div>

Ответы [ 3 ]

0 голосов
/ 07 ноября 2018

Я склонен считать, что библиотеки значительно облегчают работу с датами, и, хотя здесь может быть слишком сложно использовать их для чего-то относительно небольшого, вам может быть интересно посмотреть, как будет работать такая опция:

var test = dateFns;


function comparedate(){
    var borndate = dateFns.parse(document.getElementById("borndate").value);
    var date = dateFns.parse(new Date());
    
    console.dir(date)
    console.dir(borndate)
    
    if (dateFns.isAfter(borndate, date)) {
        alert("Looks like you are to young!");
    } else {
        return true;
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>
<div class="form">
    <form class="login-form" method="POST" action="main.php">
        <input type="date" id="borndate" name="borndate" required="required"/>
    </form>
    <button onclick="comparedate()">Compare</button>
</div>
0 голосов
/ 07 ноября 2018

Попробуйте:

// You were wrong comparing only the year with the full date
var todaysYear = new Date().getFullYear();

var borndate = document.getElementById("borndate");
var form = document.querySelector("form");
// Working with forms we want to catch submit (not click) events
form.addEventListener('submit', comparedate)

function comparedate(evt) {
  // preventing default behavior (form submit in this case)
  evt.preventDefault();

  // here we translate 'string' value back to 'date' & extract year
  var yearOfBirth = new Date(borndate.value).getFullYear()
  // an alternative would be to simply parse the year off the string itself

  if (yearOfBirth >= todaysYear) {
    alert("Looks like you are to young!");
  } else {
    // submitting form programmatically
    form.submit()
  }
}
<div class="form">
  <form class="login-form" method="POST" action="main.php">
    <input type="date" id="borndate" name="borndate" required="required" />
    <input type="submit" class="button" name="button" value="submit" />
  </form>
</div>
0 голосов
/ 07 ноября 2018

Поскольку переменная date - это год, я предполагаю, что вы пытаетесь сравнить только год.

Ваш код сравнивает сам элемент с годом. Вы должны сделать сравнение со значением элемента.

Изменить

if (borndate >= date)

К

if (new Date(borndate.value).getFullYear() >= date)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...