i need some help to solve my problem. I’ve got 2 input field with a mask ( http://digitalbush.com/projects/masked-input-plugin/ ) like that > 12/2010 ( mm/yyyy ).
I want that user could register form when a date is valid or leave blank, and send an alert in a div when a date is invalid.
It’s working fine if i’ve got 1 field, but when i have 2 field, if user enter a valid date in the second, he can register the form.
Else, if you have any idea to restrict end date that can be before the start date …
Thanks for any help 😉
My HTML code :
<form id="blockdate">
<div>date start: <input class="date" type="text"></div>
<div>date end: <input class="date2" type="text"></div>
<div><input class="submit" type="submit"></div>
<div id="msg"></div>
</form>
My JS code :
function verifyDate(datevalue) {
var done = false;
if(datevalue != null || datevalue != ''){
var tmp = datevalue.split('/');
var month = tmp[0];
var year = tmp[1];
if(month >= 1 && month <= 12){
if(year >= 1990 && year <= 2099){
clean();
done = true;
}
else {
$('#msg').html('Year invalid 1900 - 2099.');
}
} else {
$('#msg').html('Month invalid');
}
} if (datevalue < 1 ) {
done = true;
}
return done;
}
function verifyDate2(datevalue2) {
var done = false;
if(datevalue2 != null || datevalue2 != ''){
var tmp = datevalue2.split('/');
var month = tmp[0];
var year = tmp[1];
if(month >= 1 && month <= 12){
if(year >= 1990 && year <= 2099){
clean();
done = true;
}
else {
$('#msg').html('Year invalid 1900 - 2099.');
}
} else {
$('#msg').html('Month invalid');
}
} if (datevalue2 < 1 ) {
done = true;
}
return done;
}
function clean() {
$('#msg').html('');
}
jQuery(function($) {
$(".date").mask("99/9999");
$('.blockdate').submit(function() {
var datevalue = $('.date').val();
var datevalue2 = $('.date2').val();
return verifyDate(datevalue);
});
$(".date").change(function(){
var datevalue = $(this).val();
if(datevalue.length == 7) {
verifyDate(datevalue);
} else {
clean();
}
});
jQuery(function($) {
$(".date2").mask("99/9999");
$('.blockdate').submit(function() {
var datevalue2 = $('.date2').val();
return verifyDate2(datevalue2);
});
$(".date2").change(function(){
var datevalue2 = $(this).val();
if(datevalue2.length == 7) {
verifyDate2(datevalue2);
} else {
clean();
}
});
});
});
I can slightly simplify your task by providing a small regex.
use it this way
It checkes weather the first part, i.e. lies between 1 and 12 and the second part between 1990 and 2099.
EDIT
After you have tested the correctness of the format you can see the range as follows
There is a small math trick.