首頁  >  文章  >  web前端  >  jQuery實作驗證年齡簡單思路_jquery

jQuery實作驗證年齡簡單思路_jquery

WBOY
WBOY原創
2016-05-16 15:13:551232瀏覽

這段程式碼假定環境是一個ID為age-form的”form”,三個ID分別為”day”,”month”,”year”。

$("#age-form").submit(function(){
  var day = $("#day").val();
  var month = $("#month").val();
  var year = $("#year").val();
  var age = 18;
  var mydate = new Date();
  mydate.setFullYear(year, month-1, day);

  var currdate = new Date();
  currdate.setFullYear(currdate.getFullYear() - age);
  if ((currdate - mydate) < 0){
    alert("Sorry, only persons over the age of " + age + " may enter this site");
    return false;
  }
  return true;
});

也許你想使用一個比alert更優雅的提示方法。並且應該在伺服器端進行再次驗證,不然只能在啟用js的客戶端驗證。

反正程式碼的意思是讓使用者填出生年月,然後根據當前時間計算是否小於網站要求的年齡,小於就提示。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn