如何在只读字段上启用jquery验证?

Dan*_*eda 20 jquery datepicker readonly jquery-validate

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

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

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

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

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

Dan*_*eda 40

谢谢你的建议Panoptik,增加readonlyfocusin,然后于消除它focusout是最干净的方式,千万感谢!如果有人遇到同样的问题,我会自己回答.希望能帮助到你.

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

$(document).on("focusout", "#someid", function() {
   $(this).prop('readonly', false); 
});
Run Code Online (Sandbox Code Playgroud)


saf*_*fer 10

除了readonly字段处理之外,您可以使用与原始实现非常相似的实现覆盖原始"elements"函数.这不是一个优雅的解决方案,但确实有效.如果更新jquery验证库,则还需要重新检查已重写的方法.
*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;
    });         
};
Run Code Online (Sandbox Code Playgroud)