我寫了一些代碼來檢查兩個日期 - 它們被分成兩天輸入(#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