這段代碼假定環境是一個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的客戶端驗證。
反正代碼的意思就是讓用戶填出生年月,然后根據當前時間計算是否小于網站要求的年齡,小于就提示。
新聞熱點
疑難解答