简体   繁体   中英

Custom javascript date field return NaN

I have added a custom javascript date field but when I enter date more than 12 dates in the day(DD) then the final value return NaN but when I enter less than 12 in DD then its working fine. Here is my html code

 var el = document.getElementById("dateField"); el.onkeyup = function(evt) { if ((evt.keyCode >= 48 && evt.keyCode <= 57) || (evt.keyCode >= 96 && evt.keyCode <= 105)) { evt = evt || window.event; var size = document.getElementById('dateField').value.length; if ((size == 2 && document.getElementById('dateField').value > 31) || (size == 5 && Number(document.getElementById('dateField').value.split('/')[1]) > 12) || (size == 10 && Number(document.getElementById('dateField').value.split('/')[2]) > 2017)) { alert('Invalid Date'); document.getElementById('dateField').value = ''; return; } if ((size == 2 && document.getElementById('dateField').value < 32) || (size == 5 && Number(document.getElementById('dateField').value.split('/')[1]) < 13)) { document.getElementById('dateField').value += '/'; } } var birthDay = document.getElementById("dateField").value; var DOB = new Date(birthDay); var today = new Date(); var age = today.getTime() - DOB.getTime(); age = Math.floor(age / (1000 * 60 * 60 * 24 * 365.25)); alert(age); }
 <div class="custom-date-field"> <p><label>DOB <span>Enter the date</span></label> <input id="dateField" type="text" placeholder="DD/MM/YYYY"> </p> </div>

just use type="date" placeholder="YYYY-MM-DD" the input field will be localized to the users preferred format. The placeholder is just an fallback if the browser won't do it. What you always going to get back is an standard ISO format back ( YYYY-MM-DD ) so you can parse it the same way all the time. like @VLAZ said your format is non standard...

I think a native picker is more superior then custom ones for some reason

 $bday.max = new Date().toJSON().split('T')[0] $bday.onchange = () => { console.log($bday.value) console.log($bday.valueAsDate) console.log(((Date.now() - $bday.valueAsNumber) / 3.15576e+10)|0 ) // age }
 <input id="$bday" type="date" autocomplete="bday" min="1800-01-01" placeholder="YYYY-MM-DD">

on the plus side you will get better auto completion, built in validation and better accessibility that browser and other disabled people can understand easier

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM