【问题标题】:AngularJS: validate ng-disabled / ng-readonly fieldsAngularJS:验证 ng-disabled / ng-readonly 字段
【发布时间】:2015-09-08 07:12:57
【问题描述】:

我写了this jsFiddle 来描述手头的问题。基本上我有一个带有某些ng-required 文本输入的表单。问题是用户无法在其中输入,但必须单击一个按钮,该按钮会打开一个包含允许值列表的对话框;单击一个会相应地设置输入的ng-model(在我的示例中,输入旁边的按钮会立即设置ng-model,但您会明白)。
麻烦的是,如果我设置ng-disabled(可理解)或ng-readonly(老实说我不知道​​为什么),即使该字段为空,表单也会提交,而我想强制用户输入。我怎么能做到这一点?干杯。

【问题讨论】:

  • 你需要为这个案例写下你自己的有效...

标签: javascript angularjs forms validation


【解决方案1】:

我通过添加另一个共享相同模型的输入并将其放在可见模型的正下方来解决这个问题。但是,您不能只进行隐藏输入(通过设置 type="hidden" 或 ng-hide 等等),因为完全隐藏它不会让验证显示出来。

<!-- Normal input: we want this to be required, yet read-only -->    
<input id="inputMyValue" ng-model="myValue" ng-click="openSelectionDialog()" ng-readonly="true"/>

<!-- Hidden input: not really hidden - just visible enough for the validation to work -->
<input id="inputMyValueHidden" ng-model="myValue" ng-required="true"  style="height: 0; border: 0;"/>

【讨论】:

    【解决方案2】:

    在提交时编写您自己的验证函数:

    $scope.validateForm = function() {
        if ($scope.myDisabledInput === '') {
            return;
        }
    };
    

    我会以某种方式提醒用户,但这至少应该为您指明正确的方向。

    【讨论】:

    • 我想这总比没有好,虽然我希望利用 ng-required 属性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    相关资源
    最近更新 更多