date validation in javascript – Validate Date Using Regular Expressions, the moment.js Library and Date.parse() Method in JavaScript Example with demo.
How to check a date is valid or not using JavaScript?
A JavaScript function is used to check a valid date format against a regular expression.
Date Validation as Text Format in JavaScript
Validation Function
function validatedate(dateString){ let dateformat = /^(0?[1-9]|1[0-2])[\/](0?[1-9]|[1-2][0-9]|3[01])[\/]\d{4}$/; if(dateString.match(dateformat)){ let operator = dateString.split('/'); let secDateInfo = []; if (operator.length>1){ secDateInfo = dateString.split('/'); } let curr_mon= parseInt(secDateInfo[0]); let day = parseInt(secDateInfo[1]); let year = parseInt(secDateInfo[2]); let totalNoOfDays = [31,28,31,30,31,30,31,31,30,31,30,31]; if (curr_mon==1 || curr_mon>2){ if (day>totalNoOfDays[curr_mon-1]){ return false; } }else if (curr_mon==2){ let applpYear = false; if ( (!(year % 4) && year % 100) || !(year % 400)) { applpYear = true; } if ((applpYear == false) && (day>=29)){ return false; }else if ((applpYear==true) && (day>29)){ console.log('Sorry, Invalid date format!'); return false; } } }else{ console.log("Invalid date format!"); return false; } return true; }
Example
var a = validatedate("06/16/2021"); console.log(a);
Sample Regex for Date Format
Date Format | Regex |
MM/DD/YYYY | |
M/DD/YYYY | /^(0?[1-9]|1[0-2])[\/](0?[1-9]|[1-2][0-9]|3[01]) |
MM/D/YYYY | [\/]\d{4}$/ |
M/D/YYYY | |
DD/MM/YYYY | |
D/MM/YYYY | /^(0?[1-9]|[1-2][0-9]|3[01])[\/](0?[1-9]|1[0-2]) |
DD/M/YYYY | [\/]\d{4}$/ |
D/M/YYYY |
Don’t Miss : Timestamp To Date Javascript
Validate Date With With Date.parse() Method in JavaScript
Date Validation as Text Format in JavaScript – The Data.parse() is a function that is already available in core JavaScript.
Validate Date With With Date.parse() Method in JavaScript - www.pakainfo.com
Validate Date Using Regular Expressions in JavaScript
Document
Validate Date With the moment.js Library in JavaScript
First of all open your cmd terminal and run this bellow commands.
npm install -g moment --save
Example
import * as moment from 'moment'; let result = moment("05/22/21", 'MM/DD/YY',true).isValid(); console.log(result)
Date of Birth (Age) Validation in JavaScript
HTML Markup
Date of Birth (Age) Validation in JavaScript
Don't Miss : How To Get Current Date & Time In JavaScript?
I hope you get an idea about date validation in javascript.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.