2009-08-25 3 views
2

Я написал код, который будет проверять две даты - они разбиты на два дня (# 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!^

}

Извините, если это кажется, что я задать глупый вопрос, так как мой код работает нормально, я просто думаю, что это мусорный путь делая это, с множеством повторений, но я не могу думать о каком-либо способе сделать это более эффективно?

Благодаря

ответ

2
function validate_form_checks() { 
    var error; 
    // check whether the available hours they've entered are a valid time! 
    $(':text').each(function() { 
     if(isNaN($(this).val())) { 
      $(this).focus(); 
      error = 'Please enter a valid date!'; 
      return false; 
     } 
    }); 
    if(error) 
     return error; 
    $('#date-1-dd, #enddate-1-dd').each(function() { 
     if($(this).val() > 31) { 
      $(this).focus(); 
      error = 'Please enter a valid day, should be no more than 31!'; 
      return false; 
     } 
    }); 
    if(error) 
     return error; 
    $('#date-1-mm, #enddate-1-mm').each(function() { 
     if($(this).val() > 12) { 
      $(this).focus(); 
      error = 'Please enter a valid month, should be no more than 12!'; 
      return false; 
     } 
    }); 
    if(error) 
     return error; 
    $('#date-1, #enddate-1').each(function() { 
     if($(this).val() < 1900 || $(this).val() > 3000) { 
      $(this).focus(); 
      error = 'Please enter a valid year!'; 
      return false; 
     } 
    }); 
    if(error) 
     return error; 
    return true; 
} 

function validate_form() { 
    var result = validate_form_checks(); 
    if(result === true) { 
     return true; 
    } else { 
     $.jGrowl(result, { theme: 'smoke' }); 
     return false; 
    } 
} 

Конечно, проверка, которая обеспечивает обратную связь на все ошибки в форме, а не только первый является своего рода, y'know, лучше.

+0

Это фантастика, спасибо! – Nick

1

На первый взгляд, вы могли бы создать функцию из этих одинаковых секций и просто называют его по мере необходимости. You shouldn't repeat yourself.

Описание: blog post о подтверждении дат, которые могут быть полезными. И вот ответ SO, который дает оценку jQuery plugin answer.

+0

Что SO означает в этом контексте? Я видел это до сегодняшнего дня! – Dorjan

+0

StackOverflow. Сайт, на котором вы находитесь. – chaos

+1

Некоторые полезные ресурсы здесь, спасибо – Nick

0

Да, здесь:

function validate_form() { 
return retVal = !0, retVal == 1 && $(":text") 
    .each(function() { 
    return $this = $(this), isNaN($this.val()) ? ($this.focus(), $.jGrowl("Please enter a valid date!", { 
     theme: "smoke" 
    }), retVal = !1, !1) : void 0 
}), retVal == 1 && $("#date-1-dd") 
    .each(function() { 
    return $this = $(this), $this.val() > 31 ? ($this.focus(), $.jGrowl("Please enter a valid day, should be no more than 31!", { 
     theme: "smoke" 
    }), retVal = !1, !1) : void 0 
}), retVal == 1 && $("#enddate-1-dd") 
    .each(function() { 
    return $this = $(this), $this.val() > 31 ? ($this.focus(), $.jGrowl("Please enter a valid day, should be no more than 31!", { 
     theme: "smoke" 
    }), retVal = !1, !1) : void 0 
}), retVal == 1 && $("#date-1-mm") 
    .each(function() { 
    return $this = $(this), $this.val() > 12 ? ($this.focus(), $.jGrowl("Please enter a valid month, should be no more than 12!", { 
     theme: "smoke" 
    }), retVal = !1, !1) : void 0 
}), retVal == 1 && $("#enddate-1-mm") 
    .each(function() { 
    return $this = $(this), $this.val() > 12 ? ($this.focus(), $.jGrowl("Please enter a valid month, should be no more than 12!", { 
     theme: "smoke" 
    }), retVal = !1, !1) : void 0 
}), retVal == 1 && $("#date-1") 
    .each(function() { 
    return $this = $(this), 1900 > $this.val() || $this.val() > 3e3 ? ($this.focus(), $.jGrowl("Please enter a valid year!", { 
     theme: "smoke" 
    }), retVal = !1, !1) : void 0 
}), retVal == 1 && $("#enddate-1") 
    .each(function() { 
    return $this = $(this), 1900 > $this.val() || $this.val() > 3e3 ? ($this.focus(), $.jGrowl("Please enter a valid year!", { 
     theme: "smoke" 
    }), retVal = !1, !1) : void 0 
}), retVal 
} 
Смежные вопросы