Reputation: 946
I have this datepicker
which is defined as date-picker
class.
I want to check if the date is valid, I mean when the user modifies the date by keyboard, for example if enters day more than 31 or month more than 12 it should give an error.
I have written this isValidDate
function but it does not work fine. I read somewhere that there is a valid()
function for datepickers.
$(function() {
$(".date-picker").datepicker({
dateFormat: 'dd/mm/yy'
});
$(".date-picker").each(function() {
$(this).add($(this).next()).wrapAll('<div class="imageInputWrapper"></div>');
});
$('input:button').click(function(e) {
$("#fDate").removeClass("red");
var fromDate = $("#fDate").val();
if (!isValidDate(fromDate)) {
$("#fDate").addClass("red");
}
if (errors) e.preventDefault();
});
function isValidDate(date) {
var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
if (matches == null) return false;
var d = matches[2];
var m = matches[2];
var y = matches[3];
if (y > 2100 || y < 1900) return false; // accept only recent & not too far years
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d && composedDate.getMonth() == m && composedDate.getFullYear() == y;
}
});
.imageInputWrapper {
width: 172px;
border: solid 1px white;
background-color: white;
display: flex;
align-items: center;
box-shadow: 0 2px 2px 0 #C2C2C2;
}
.red {
box-shadow: 0px 0px 2px 2px red;
}
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<form>
<input id="fDate" class="date-picker" type="text" name="fromDate" style="width: 130px; height: 41px; background-color: white; border: none; outline: none; margin-left:5px" />
<img src="http://s9.postimg.org/nl2mcq2rv/calendar.png" id="fromDateImgId">
<br/>
<input type="button" value="submit">
</table>
</form>
if you insert 44 in the day section it won't give any error in my code.
Upvotes: 0
Views: 7385
Reputation: 501
Your code works fine. Just a little bit tweaks.
function isValidDate(date) {
var matches = /^(\d+)[-\/](\d+)[-\/](\d+)$/.exec(date);
if (matches == null) return false;
var d = matches[1];
var m = matches[2];
var y = matches[3];
if (y > 2100 || y < 1900) return false;
var composedDate = new Date(y+'/'+m+'/'+d);
return composedDate.getDate() == d && composedDate.getMonth()+1 == m && composedDate.getFullYear() == y;
}
Working fiddle: https://jsfiddle.net/ppw1k3yu/1/
Upvotes: 1
Reputation: 27
You can use Date.parse()
for your validate function.
Example
function isValidDate(str) {
return !isNaN(Date.parse(str));
}
Upvotes: 1