我写了一些代码来检查两个日期 - 它们被分成两天输入(#enddate-1-dd,#date-1-dd),两个月输入(#enddate-1-mm,#date -1毫米)和两年的输入(#enddate-1,#date-1)我可以简化/优化这个Jquery代码吗?
我想首先检查他们都是实际的数字,但后来我想检查每一个以确保它的日期格式,此刻是这样的:
function validate_form() {
retVal = true; // if the statements below fail, return true
if(retVal == true) {
// check whether the available hours they've entered are a valid time!
$(":text").each(function() {
$this = $(this); // cache the object
if (isNaN($this.val())) {
$this.focus();
$.jGrowl('Please enter a valid date!', { theme: 'smoke' });
retVal = false; return false;
}
});
}
if(retVal == true) {
$("#date-1-dd").each(function() {
$this = $(this); // cache the object
if ($this.val() > 31) {
$this.focus();
$.jGrowl('Please enter a valid day, should be no more than 31!', { theme: 'smoke' });
retVal = false; return false;
}
});
}
if(retVal == true) {
$("#enddate-1-dd").each(function() {
$this = $(this); // cache the object
if ($this.val() > 31) {
$this.focus();
$.jGrowl('Please enter a valid day, should be no more than 31!', { theme: 'smoke' });
retVal = false; return false;
}
});
}
if(retVal == true) {
$("#date-1-mm").each(function() {
$this = $(this); // cache the object
if ($this.val() > 12) {
$this.focus();
$.jGrowl('Please enter a valid month, should be no more than 12!', { theme: 'smoke' });
retVal = false; return false;
}
});
}
if(retVal == true) {
$("#enddate-1-mm").each(function() {
$this = $(this); // cache the object
if ($this.val() > 12) {
$this.focus();
$.jGrowl('Please enter a valid month, should be no more than 12!', { theme: 'smoke' });
retVal = false; return false;
}
});
}
if(retVal == true) {
$("#date-1").each(function() {
$this = $(this); // cache the object
if ($this.val() < 1900 || $this.val() > 3000) {
$this.focus();
$.jGrowl('Please enter a valid year!', { theme: 'smoke' });
retVal = false; return false;
}
});
}
if(retVal == true) {
$("#enddate-1").each(function() {
$this = $(this); // cache the object
if ($this.val() < 1900 || $this.val() > 3000) {
$this.focus();
$.jGrowl('Please enter a valid year!', { theme: 'smoke' });
retVal = false; return false;
}
});
}
return retVal; // return either true or false, depending on what happened up there!^
}
很抱歉,如果它看起来像我问一个愚蠢的问题,我的代码工作没关系,我只是觉得这是一个垃圾的方式这样做,带着大量的重复,但我真的想不出更有效率的方法吗?
感谢
这太棒了,谢谢! – Nick 2009-08-26 09:00:42