2011-03-31 89 views
0

我很新的jQuery验证插件。尝试比较两个字段中的日期值,并在一个日期早于另一个日期时触发错误。这里是标记:为什么此回调不起作用的JQuery验证?

 <label>Last prescription fill date:</label> 
     <input type="text" ID="InputLastPrescriptionFillDate" 
      style="width: 200px" 
      Class="calendarSelectInput dateComparison required" /> 
     <br /> 
     <label>Prescription start date:</label> 
     <input type="text" ID="InputPrescriptionStartDate" name="InputPrescriptionStartDate" 
      style="width: 200px" 
      Class="calendarSelectInput dateComparison required" /> 

这里是jQuery。

$(document).ready(function() { 
    $("form").validate({ 
      rules: { 
       InputPrescriptionStartDate: { 
        required: compareRxDates() 
       } 
      }, 
      messages: { 
       InputPrescriptionStartDate: { 
        required: "Last prescription fill date should not be after the prescription start date." 
       } 
      } 
    }); 
}); 

和回调javascript。

function compareRxDates() { 
    return new Date($("#InputPrescriptionStartDate").val()) < new Date($("#InputLastPrescriptionFillDate").val()); 
} 

...它在document.ready上被调用,但是只要字段中的值发生变化,就不会被调用。我试图在这些字段的变化事件中包装form.validate,但是这个函数仍然没有被调用。

我在做什么错?这是我正在尝试做的正确方法吗?

回答

0

看来你正在将compareRxDates()分配给required属性,该属性应该是一个布尔值 - true或false,告诉插件是否需要该字段。你应该把你的回调放在depends属性中。

实施例:

$("form").validate({ 
    rules: { 
     InputPrescriptionStartDate: { 
      depends: function(element) { 
       compareRxDates(); 
      } 
     } 
    }, 
// etc 

从文档:

每个规则可被指定为具有取决于属性仅在某些条件下

UPDATE应用规则:(提出一个更好的,可重用的解决方案,举例)

您可以添加自己的验证方法,可以重复使用于其他领域,像这样:

jQuery.validator.addMethod("shouldBeGreaterThan", function(value, currentElement, argumentElement) { 
    return value > $(argumentElement).val(); 
}, "* This field should be greater than the other"); 

$("form").validate({ 
    rules: { 
     InputPrescriptionStartDate: { 
      shouldBeGreaterThan: $("#InputLastPrescriptionFillDate") 
     } 
    } 
}); 

addMethod功能临危3个参数。方法名称,评估函数和一个消息,如果它的计算结果为false(可以覆盖个别元素),将显示该消息。在上面的例子中,我做了一个验证方法,要求参数元素的值应该大于当前值。这可以很容易地更改为使用日期。

继承人与工作示例的jsfiddle:http://jsfiddle.net/bZzrs/5/

+0

感谢回答。我试了一下,却无法让它工作。 – Marvin 2011-03-31 02:04:19

+0

我更新了我的答案,但我看到我有点迟了:) – Daniel 2011-03-31 02:19:21

+0

感谢您的帮助!我无法获得第一个解决方案,但第二个解决方案对我很好。 – Marvin 2011-03-31 02:27:01

0

这里是我工作:

jQuery.validator.addMethod("beforeFillDate", function(value, element) { 
    var rxDate = new Date(value); 
    var lastFillDate = new Date($("#InputLastPrescriptionFillDate").val()); 
    return rxDate > lastFillDate; 
}, "Last prescription fill date should not be after prescription start date."); 

然后......

$("form").validate({ 
    rules: { InputPrescriptionStartDate: { beforeFillDate: true}} 
});