如何在只读字段上启用jqueryvalidation?

来自http://jqueryvalidation.org/的人刚刚发布了1.13.1版。 检查他们的网站我在更改日志上看到这个:

核心:*忽略只读和禁用字段。 (9f4ba10)

这是链接: https : //github.com/jzaefferer/jquery-validation/commit/9f4ba10ea79b4cf59225468d6ec29911f0e53a0a

我使用了一些引导程序模板,其中一个现在使用该版本。 这给我带来了一个问题,我使用readonly属性来阻止用户手动输入日期,因此他们唯一的选择是从datepicker中选择一个日期。

通过此更改,validation插件会忽略标记为必需的只读输入,是否有人可以帮我建议1.13.1或未来版本的某些修复? 我发现了一个相反的问题: 如何在readonly字段上禁用jqueryvalidation?

谢谢你的建议focusin ,在focusin上添加readonly ,然后在focusout上删除它是最干净的方式, focusout感谢! 如果有人遇到同样的问题,我会自己回答。 希望能帮助到你。

 $(document).on("focusin", "#someid", function() { $(this).prop('readonly', true); }); $(document).on("focusout", "#someid", function() { $(this).prop('readonly', false); }); 

除了readonly字段处理之外,您可以使用与原始实现非常相似的实现覆盖原始“elements”函数。 这不是一个优雅的解决方案,但确实有效。 如果更新jqueryvalidation库,则还需要重新检查已重写的方法。
* UpToDate *请参阅jquery-validate-1.14 changeLog :恢复“忽略只读和禁用字段”。 🙂 🙂

 $.validator.prototype.elements = function() { var validator = this, rulesCache = {}; return $( this.currentForm ) .find( "input, select, textarea" ) .not( ":submit, :reset, :image, [disabled]") // changed from: .not( ":submit, :reset, :image, [disabled], [readonly]" ) .not( this.settings.ignore ) .filter( function() { if ( !this.name && validator.settings.debug && window.console ) { console.error( "%o has no name assigned", this ); } if ( this.name in rulesCache || !validator.objectLength( $( this ).rules() ) ) { return false; } rulesCache[ this.name ] = true; return true; }); }; 

我不喜欢绑定到focusin / out事件。 它还要求您添加CSS样式。 下面的代码删除了readonly属性,并在表单无效时重新应用它。

 $('#form').submit(function () { var children = $(this).find('input[readonly]'); children.prop('readonly', false); var validform = $(this).valid(); if (validform) { $(this).unbind('submit').submit(); } else { children.prop('readonly', true); } e.preventDefault(); e.stopPropagation(); }) 

在触发的focusin事件上设置readonly属性的解决方案很好,但是需要我们在块中编写处理程序(为什么?例如,Firefox不支持输入元素的onfocusin attr)。

所以,在我看来, 简单和跨平台的解决方案onkeydown="return false;" 属性如:

这使得元素有资格进行validation,并且不允许在其中输入任何内容。