【问题标题】:jquery validate using multiple variablejquery使用多个变量验证
【发布时间】:2013-08-06 22:02:54
【问题描述】:

我的 html 中有 3 个变量:

  1. 开始日期(文本输入)

    <input size="16" name="start_date" type="text"  class="m-wrap">
    
  2. 结束日期(文本输入)

    <input size="16" name="end_date" type="text"  class="m-wrap">
    
  3. 频率(下拉菜单)

    <select class="span3 chosen" name="summarize" tabindex="1">
       <option value="1">15 minutes</option>
       <option value="2">30 minutes</option>
       <option value="3">1 hour</option>
       <option value="4">3 hours</option>
    </select>
    

我想使用 jquery 在 3 个变量之间进行验证输入,如果 diff(start_date 和 end_date) > 3 个月,summary 只能用于值 >= 1 小时(值 3 和 4)。 id=Form_1 中的所有这些变量。

如何进行此验证?任何示例代码将不胜感激。

【问题讨论】:

  • 我建议将此插件与自定义验证规则一起使用。 jqueryvalidation.org
  • 你的最后一部分很不清楚。和@CharliePrynn 我不认为这个插件可以完成那个特定的任务..
  • 插件接受自定义方法(规则)。该函数将根据日期比较的结果返回真/假。
  • @RoyiNamir 在表单提交期间,我想检查 start_date、end_date 和总结的输入,如果 start_date 和 end_date 之间的差异 >= 3 个月,那么总结的值应该 >= 1 小时
  • @CharliePrynn 这个插件不会给他写东西,他还是要写JS。他在问核心的js逻辑

标签: jquery validation


【解决方案1】:

我假设您正在使用 jQuery 验证插件。如果不是,该逻辑仍然可以使用。我承认它非常粗糙。将以下方法添加到additional-methods.js。该文件与jquery.validate.js 一起提供。

jQuery.validator.addMethod("frequency", function(value, element) {
  var startdate = Date.parse($('input[name="start_date"]').val();
  var enddate = Date.parse($('input[name="end_date"]').val();
  difference = enddate-startdate;
  if(difference>7776000){
    if(value>2)
      return true;
    else
      return false;
  }
  else
    return true;
}, "Enter a higher frequency");

现在将frequency 类添加到您的频率选择框中。 不要忘记在您的 html 中包含 additional-methods.js 文件。这为验证添加了一个新的自定义规则。随意修补。

【讨论】:

    【解决方案2】:
    $(function () {
    
        $('input[name="start_date"], input[name="end_date"]')
        .change(function () {
    
            // check that both dates are populated and valid, if not than return
    
            // if the difference between the start date and the end date is more than
            // three months, than hide options less than an hour, otherwise return
            $('select[name="summarize"] > option:lt(2)').hide();
    
        });
    
    });
    

    Detecting an "invalid date" Date instance in JavaScript

    Get difference between 2 dates in javascript?

    【讨论】:

      【解决方案3】:

      试试jQuery UI Validation。在这里,您可以轻松定义自定义规则验证,然后分配给输入字段。如果您遇到任何问题,请告诉我。

      【讨论】:

        猜你喜欢
        • 2021-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-16
        • 1970-01-01
        • 2012-04-30
        • 2014-10-09
        相关资源
        最近更新 更多