Skip to content

Instantly share code, notes, and snippets.

@anujsinghwd
Last active May 23, 2018 11:50
Show Gist options
  • Save anujsinghwd/944d01fcb32f3ca024c80a94452b3c9c to your computer and use it in GitHub Desktop.
Save anujsinghwd/944d01fcb32f3ca024c80a94452b3c9c to your computer and use it in GitHub Desktop.
validate date and also reformat date
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Checking Date</title>
<style>
li {
list-style-type: none;
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 400px;
background: #D8F1F8;
border: 1px soild silver;
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 17pt;
}
input:focus,
textarea:focus {
background-color: lightyellow;
}
input submit {
font-size: 12pt;
}
.rq {
color: #FF0000;
font-size: 10pt;
}
#result {
margin-left: 10px;
}
</style>
</head>
<body>
<div class="mail">
<h2>Input a date [mm/dd/yyyy or mm-dd-yyyy format]</h2>
<ul>
<li>
<input type='text' id='input' />
</li>
<li>&nbsp;</li>
<li class="submit">
<input type="submit" name="submit" value="Validate Date" onclick="ValidateDate()" />
</li>
<li>&nbsp;</li>
<li class="submit">
<input type="submit" name="submit" value="Reformat Date" onclick="reformatDate()" />
</li>
<li>&nbsp;</li>
</ul>
<li id="result"></li>
</div>
<script>
var matches;
function isValidDate(date) {
matches = /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{2,4})$/.exec(date);
if (matches == null) return false;
var d = matches[1];
var m = matches[2] - 1;
var y = matches[3];
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d && composedDate.getMonth() == m && composedDate.getFullYear() == y;
}
function ValidateDate() {
var date = document.getElementById('input').value;
if (isValidDate(date)) {
document.getElementById('result').innerHTML = 'Date is Valid';
}
else {
document.getElementById('result').innerHTML = 'Date is InValid';
}
}
function reformatDate() {
var date = document.getElementById('input').value;
if (isValidDate(date)) {
var res = (matches[0].indexOf('-') !== -1) ? matches[0].split("-").reverse().join("/") : matches[0].split("/").reverse().join("-");
document.getElementById('result').innerHTML = 'New Format : ' + res;
}
else {
document.getElementById('result').innerHTML = 'Date is InValid';
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment