June 17, 2020
How to Validate Date in Javascript
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div> <input type="text" placeholder="MM" id="month"> <input type="text" placeholder="DD" id="date"> <input type="text" placeholder="YYYY" id="year"> <button>Check</button> <h1>Result</h1> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <script src="script.js"></script> </body> </html> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
body { text-align: center; } div { display: inline-block; } input, button { display: inline-block; padding: 10px 20px; } #month, #date { width: 3%; } #year{ width: 10%; } |
Javascript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
let btnCheck = document.querySelector('button'); let inputMonth = document.querySelector('#month'); let inputDate = document.querySelector('#date'); let inputYear = document.querySelector('#year'); let result = document.querySelector('h1'); btnCheck.addEventListener('click', (event) => { let month = inputMonth.value; let year = inputYear.value; let date = inputDate.value; // true in the end, so that our date string and date format should match exactly - in moment js it is called Strict Parsing result.innerText = moment(`${month}/${date}/${year}`, 'MM/DD/YYYY', true).isValid(); }); |