Reputation: 121
i have set a jquery class:
$(function() {
$( ".datepickerIT" ).datepicker({
showOtherMonths: true,
selectOtherMonths: true,
showAnim: "clip",
dateFormat: "dd/mm/yy",
minDate: "01/01/1925",
maxDate: "31/12/2050",
changeMonth: true,
changeYear: true,
yearRange: "1925:2050",
regional: "it"
});
});
I want to add a date check control that alert if user input not is a valid date
How can add to the class ".datepickerIT" a check like this?
onClose: function(dateText, inst) {
try {
$.datepicker.parseDate('dd/mm/yy', dateText);
} catch (e) {
alert(e);
};
And what plugin i must include into head section?
Upvotes: 12
Views: 68276
Reputation: 1897
You can validate the date in following ways (you don't need a plugin for it):-
$(document).ready(function(){
$("#datepicker").datepicker();
$("#datepicker").blur(function(){
val = $(this).val();
val1 = Date.parse(val);
if (isNaN(val1)==true && val!==''){
alert("error")
}
else{
console.log(val1);
}
});
});
UPDATE: Correct approach is mentioned by @Razan Paul
Upvotes: 8
Reputation: 3586
Date.parse() does not support dd/mm/yyyy and datepicker getDate sets date to current on any parse error hence this bespoke check using new Date(yyyy, mm, dd) to verify date parts are consistent after conversion:
$(function() {
$(".datepickerIT")
.datepicker({
showOtherMonths: true,
selectOtherMonths: true,
showAnim: "clip",
dateFormat: "dd/mm/yy",
minDate: "01/01/1925",
maxDate: "31/12/2050",
changeMonth: true,
changeYear: true,
yearRange: "1925:2050",
regional: "it"
})
.on('blur', function() { // This check is for dd/mm/yyyy format but can be easily adapted to any other
if(this.value.match(/\d{1,2}[^\d]\d{1,2}[^\d]\d{4,4}/gi) == null)
alert('Invalid date format');
else {
var t = this.value.split(/[^\d]/);
var dd = parseInt(t[0], 10);
var m0 = parseInt(t[1], 10) - 1; // Month in JavaScript Date object is 0-based
var yyyy = parseInt(t[2], 10);
var d = new Date(yyyy, m0, dd); // new Date(2017, 13, 32) is still valid
if(d.getDate() != dd || d.getMonth() != m0 || d.getFullYear() != yyyy)
alert('Invalid date value');
}
});
});
Upvotes: 5
Reputation: 13838
Date.parse
is not recommend to use as there are still many differences in how different hosts parse date strings. [1][2]
I would use moment for date validation.
moment(newDate, 'DD/MM/YYYY', true).isValid()
jsfiddle: http://jsfiddle.net/dw8xyzd4/
[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse [2] Why does Date.parse give incorrect results?
Upvotes: 11
Reputation: 41
$(document).ready(function(){
// Check in date
$("#in" ).datepick({
dateFormat: "mm/dd/yy",
minDate:"0+1",
maxDate: "2years",
changeMonth:true,
changeYear:true,
onSelect:function(date_text,inst){
var from = new Date(date_text);
$( "#out" ).datepicker( "option", "minDate",from);
}
});
// Check out date
});
Note:-Here in is your field name and datepick is your plugin name.
Upvotes: -1