【问题标题】:Disable Unwanted Validation in AngularJS (Conditional Validation)在 AngularJS 中禁用不需要的验证(条件验证)
【发布时间】:2015-08-17 14:28:21
【问题描述】:

我有一个需要验证的表单。

表单包含许多部分,其中一些默认情况下是禁用的。每个字段中的值都是正确的,但这违反了我的验证指令。例如,禁用时应包含 0,但可编辑时应包含其他内容。不管怎样,我给它们附加了一个禁用指令,然后把它们放下。

当我提交表单时(使用角度范围函数),if ($scope.sarfaslForm.$invalid) --> 返回 true。当我检查$scope.sarfaslForm.$error 列表时,它说我有两个无效字段。

在此博客之后,我实现了我的验证: http://blog.yodersolutions.com/bootstrap-form-validation-done-right-in-angularjs/

this thread 之后,我创建了一个指令来忽略我的一些禁用控件:

我对这个指令做了一个小改动:

.directive('hsDisableValidation', function() {
    return {
        require: '^form',
        restrict: 'A',
        link: function(scope, element, attrs,form) {
            var control;

            scope.$watch(function() {
                return scope.$eval(attrs.hsDisableValidation);
            }, function(value) {
                if (!control) {
                    control = form[element[0].name];
                    //form[element.find("input").attr("name")];
                }
                if (value === false) {
                    form.$addControl(control);
                    angular.forEach(control.$error, function(validity, validationToken) {
                        form.$setValidity(validationToken, !validity, control);
                    });
                } else {
                    form.$removeControl(control);
                    //In Here: I tried to $setValidity of controls to true, Remove Error List, and Remove Validator Function, but these things didn't worked out
                }
            });
        }
    }
})

这里的验证对我来说总是失败: PS:因为我在“文本”类型的字段中使用它,所以我没有最小/最大值,只有最小/最大长度。我确定这不是问题,但我包含此代码以确保。

.directive('hsMinValue', function() {
        return {
            require: 'ngModel',
            link: function (scope, elem, attr, ngModel) {

                function isLesser(value) {
                    var minVal = parseInt(attr.hsMinValue);
                    return parseInt(value) < minVal;
                }

                function validate(value) {
                    var valid = !isLesser(value);
                    ngModel.$setValidity('minValue', valid);
                    return valid ? value : undefined;
                }

                ngModel.$parsers.unshift(function (value) {
                    ngModel.$setValidity('minValue', !isLesser(value));
                    return value;
                });

                ngModel.$formatters.unshift(function (value) {
                    ngModel.$setValidity('minValue', !isLesser(value));
                    return value;
                });
            }
        }
    });

然后我保存:

saveSarfasl: function () {
                $scope.$broadcast('show-errors-check-validity');
                if ($scope.sarfaslForm.$invalid) { --> True :|
                    return;
                }
                //Stuffs
}

编辑:应詹姆斯的要求,我将 HTML 并在此处查看我的页面。

<div class="clearfix">
    <form name="sarfaslForm" novalidate>
        <table class="table-condensed">
            <tbody>
                <tr>
                    <td>
                        کد سرفصل
                    </td>
                    <td>
                        <table class="table-condensed">
                            <tbody>
                                <tr>
                                    <td data-ng-if="View.FinYear.LenK != 0">
                                        کل
                                    </td>
                                    <td data-ng-if="View.FinYear.LenM != 0">
                                        معین
                                    </td>
                                    <td data-ng-if="View.FinYear.LenT1 != 0">
                                        تفضیل یک
                                    </td>
                                    <td data-ng-if="View.FinYear.LenT2 != 0">
                                        تفضیل دو
                                    </td>
                                    <td data-ng-if="View.FinYear.LenJ != 0">
                                        جزء
                                    </td>
                                </tr>
                                <tr>
                                    <td data-ng-if="View.FinYear.LenK != 0">
                                        <div class="form-group" hs-show-errors hs-show-success>
                                            <input name="CodKol" type="text" hs-restrict-pattern="[^\d]*" maxlength="{{View.FinYear.LenK}}"
                                                   class="form-control input-sm"
                                                   data-ng-model="View.Kol" data-ng-disabled="View.Level!==1"
                                                   data-ng-blur="Events.codeChanged('k')"
                                                   data-ng-change="Events.setSarfaslCod()"
                                                   hs-disable-validation="View.Level!==1"
                                                   data-ng-required="true"
                                                   hs-min-value="1" />
                                            <p class="help-block" ng-if="sarfaslForm.CodKol.$error.required">
                                                کد کل الظامی می باشد
                                            </p>
                                            <p class="help-block" ng-if="sarfaslForm.CodKol.$error.minValue">
                                                کد کل نمی تواند صفر باشد
                                            </p>
                                        </div>
                                    </td>
                                    <td data-ng-if="View.FinYear.LenM != 0">
                                        <div class="form-group" hs-show-errors hs-show-success>
                                            <input name="CodMoin" type="text" hs-restrict-pattern="[^\d]*" maxlength="{{View.FinYear.LenM}}"
                                                   class="form-control input-sm"
                                                   data-ng-model="View.Moin" data-ng-disabled="View.Level!==2"
                                                   data-ng-blur="Events.codeChanged('m')"
                                                   data-ng-change="Events.setSarfaslCod()"
                                                   hs-disable-validation="View.Level!==2"
                                                   data-ng-required
                                                   hs-min-value="1" />
                                            <p class="help-block" ng-if="sarfaslForm.CodMoin.$error.required">
                                                کد معین الظامی می باشد
                                            </p>
                                            <p class="help-block" ng-if="sarfaslForm.CodMoin.$error.minValue">
                                                کد معین نمی تواند صفر باشد
                                            </p>
                                        </div>
                                    </td>
                                    <td data-ng-if="View.FinYear.LenT1 != 0">
                                        <div class="form-group" hs-show-errors hs-show-success>
                                            <input name="CodTafzil1" type="text" hs-restrict-pattern="[^\d]*" maxlength="{{View.FinYear.LenT1}}"
                                                   class="form-control input-sm"
                                                   data-ng-model="View.Tafzil1" data-ng-disabled="View.Level!==3"
                                                   data-ng-blur="Events.codeChanged('t1')"
                                                   data-ng-change="Events.setSarfaslCod()"
                                                   hs-disable-validation="View.Level!==3"
                                                   data-ng-required
                                                   hs-min-value="1" />
                                            <p class="help-block" ng-if="sarfaslForm.CodTafzil1.$error.required">
                                                کد تفظیل یک الظامی می باشد
                                            </p>
                                            <p class="help-block" ng-if="sarfaslForm.CodTafzil1.$error.minValue">
                                                کد تفظیل یک نمی تواند صفر باشد
                                            </p>
                                        </div>
                                    </td>
                                    <td data-ng-if="View.FinYear.LenT2 != 0">
                                        <div class="form-group" hs-show-errors hs-show-success>
                                            <input name="CodTafzil2" type="text" hs-restrict-pattern="[^\d]*" maxlength="{{View.FinYear.LenT2}}"
                                                   class="form-control input-sm"
                                                   data-ng-model="View.Tafzil2" data-ng-disabled="View.Level!==4"
                                                   data-ng-blur="Events.codeChanged('t2')"
                                                   data-ng-change="Events.setSarfaslCod()"
                                                   hs-disable-validation="View.Level!==4"
                                                   data-ng-required
                                                   hs-min-value="1" />
                                            <p class="help-block" ng-if="sarfaslForm.CodTafzil2.$error.required">
                                                کد تفظیل دو الظامی می باشد
                                            </p>
                                            <p class="help-block" ng-if="sarfaslForm.CodTafzil2.$error.minValue">
                                                کد تفظیل دو نمی تواند صفر باشد
                                            </p>
                                        </div>
                                    </td>
                                    <td data-ng-if="View.FinYear.LenJ != 0">
                                        <div class="form-group" hs-show-errors hs-show-success>
                                            <input name="CodJoz" type="text" hs-restrict-pattern="[^\d]*" maxlength="{{View.FinYear.LenJ}}"
                                                   class="form-control input-sm"
                                                   data-ng-model="View.Joz" data-ng-disabled="View.Level!==5"
                                                   data-ng-blur="Events.codeChanged('j')"
                                                   data-ng-change="Events.setSarfaslCod()"
                                                   hs-disable-validation="View.Level!==5"
                                                   data-ng-required
                                                   hs-min-value="1" />
                                            <p class="help-block" ng-if="sarfaslForm.CodJoz.$error.required">
                                                کد جزء الظامی می باشد
                                            </p>
                                            <p class="help-block" ng-if="sarfaslForm.CodJoz.$error.minValue">
                                                کد جزء نمی تواند صفر باشد
                                            </p>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td>
                        عنوان سرفصل
                    </td>
                    <td ng-class="{'has-error':sarfaslForm.HsbNam.$invalid && sarfaslForm.HsbNam.$dirty}">
                        <div class="form-group" hs-show-errors hs-show-success>
                            <input name="HsbNam" type="text" data-ng-model="View.Sarfasl.HsbNam"
                                   class="form-control input-sm"
                                   data-ng-required="true" />
                            <p class="help-block" ng-if="sarfaslForm.HsbNam.$error.required">
                                نام سرفصل الظامی می باشد
                            </p>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>

                    </td>
                    <td>
                        <div class="radio" hs-show-errors>
                            <label class="control-label">
                                <input type="radio" data-ng-model="View.Sarfasl.HsbKind" name="HsbKind" data-ng-value="'00'"
                                        data-ng-required="true" />
                                زیر سطح دارد
                            </label>
                        </div>
                        <div class="radio" hs-show-errors>
                            <label class="control-label">
                                <input type="radio" data-ng-model="View.Sarfasl.HsbKind" name="HsbKind" data-ng-value="'11'"
                                       data-ng-required="true" />
                                سطح آخر است
                            </label>
                            <p class="help-block" ng-if="sarfaslForm.HsbKind.$error.required">
                                انتخاب یکی از حالات الظامی می باشد
                            </p>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>

                    </td>
                    <td>
                        <div class="radio" hs-show-errors>
                            <label class="control-label">
                                <input type="radio" data-ng-model="View.Sarfasl.Permanent" name="Permanent" data-ng-value="'1'"
                                       data-ng-required="true" />
                                حساب دائم
                            </label>
                        </div>
                        <div class="radio" hs-show-errors>
                            <label class="control-label">
                                <input type="radio" data-ng-model="View.Sarfasl.Permanent" name="Permanent" data-ng-value="'0'"
                                       data-ng-required="true" />
                                حساب موقت
                            </label>
                            <p class="help-block" ng-if="sarfaslForm.Permanent.$error.required">
                                انتخاب یکی از حالات الظامی می باشد
                            </p>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>

                    </td>
                    <td>
                        <div class="radio" hs-show-errors>
                            <label class="control-label">
                                <input type="radio" data-ng-model="View.Sarfasl.AccessFlag" name="AccessFlag" data-ng-value="0"
                                       data-ng-required="true" />
                                حساب برای همه در دسترس باشد
                            </label>
                        </div>
                        <div class="radio" hs-show-errors>
                            <label class="control-label">
                                <input type="radio" data-ng-model="View.Sarfasl.AccessFlag" name="AccessFlag" data-ng-value="1"
                                       data-ng-required="true" />
                                حساب فقط برای کاربران زیر در دسترس باید
                            </label>
                            <p class="help-block" ng-if="sarfaslForm.AccessFlag.$error.required">
                                انتخاب یکی از حالات الظامی می باشد
                            </p>
                        </div>
                    </td>
                </tr>
                <tr data-ng-if="View.Sarfasl.AccessFlag==1">
                    <td>

                    </td>
                    <td>
                        <table class="table table-bordered table-hover">
                            <thead>
                            <tr>
                                <th>
                                    &nbsp;
                                </th>
                                <th>
                                    کاربران
                                </th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr data-ng-repeat="user in View.UserList">
                                <td>
                                    <div class="checkbox">
                                        <label class="control-label">
                                            <input type="checkbox" data-ng-model="user.Checked" data-ng-click="Events.userChecking(user)" />
                                        </label>
                                    </div>
                                </td>
                                <td>
                                    {{user.UserID}}
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td>

                    </td>
                    <td>
                        <!-- Hsb Types -->
                        <div class="checkbox">
                            <label class="control-label">
                                <input type="checkbox" data-ng-model="View.CheckBoxAllowRegisterLiability"
                                       data-ng-click="Events.hsbTypeChecking(View.HsbTypes.AllowRegisterLiability, View.CheckBoxAllowRegisterLiability)" />
                                اجازه ثبت بدهکاری در اسناد داشته باشد
                            </label>
                        </div>
                        <div class="checkbox">
                            <label class="control-label">
                                <input type="checkbox" data-ng-model="View.CheckBoxAllowRegisterCredits"
                                       data-ng-click="Events.hsbTypeChecking(View.HsbTypes.AllowRegisterCredits, View.CheckBoxAllowRegisterCredits)" />
                                اجازه ثبت بستانکاری در اسناد داشته باشد
                            </label>
                        </div>
                        <div class="checkbox">
                            <label class="control-label">
                                <input type="checkbox" data-ng-model="View.CheckBoxReminderShouldOnlyBeDebtor"
                                       data-ng-click="Events.hsbTypeChecking(View.HsbTypes.ReminderShouldOnlyBeDebtor, View.CheckBoxReminderShouldOnlyBeDebtor)" />
                                مانده حساب فقط باید بدهکار باشد
                            </label>
                        </div>
                        <div class="checkbox">
                            <label class="control-label">
                                <input type="checkbox" data-ng-model="View.CheckBoxReminderShouldOnlyBeCreditor"
                                       data-ng-click="Events.hsbTypeChecking(View.HsbTypes.ReminderShouldOnlyBeCreditor, View.CheckBoxReminderShouldOnlyBeCreditor)" />
                                مانده حساب فقط باید بستانکار باشد
                            </label>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        یادداشت
                    </td>
                    <td>
                        <textarea data-ng-model="View.Sarfasl.YadDasht" cols="200" rows="4" class="form-control input-sm">

                        </textarea>
                    </td>
                </tr>
                <tr>
                    <td>

                    </td>
                    <td>
                        <button type="button" class="btn btn-sm btn-primary" data-ng-click="Events.saveSarfasl()">
                            ذخیره اطلاعات
                        </button>
                        <a href="/#/Sarfasl" class="btn btn-sm btn-primary">
                            بازگشت
                        </a>
                    </td>
                </tr>
            </tbody>
        </table>
    </form>
</div>

编辑 2:

当我使用它时,所有控件都可以单独查看每个控件。 但是在我的函数中提交(提交按钮是普通按钮,没有效果,但调用我的函数)之后,我看到整体结果错误: $scope.sarfaslForm.$invalid ==> true

【问题讨论】:

  • 我可以看看你的表单的 html 标记,或者至少是你遇到问题的字段吗?
  • 我现在无法为您提供数据,因为我已经在家了,明天我可以发布准确的 HTML,但它是一团糟……但是告诉你,我的 Html,包含 7 个文本字段, 和几个收音机, 复选框, ... 6 个文本字段, 所有收音机都有验证, 这些文本字段中的 5 个, 创建一个代码, 我让它们按照我老板系统的工作方式, 所以我不能改变那个旧的系统,他要这样,所以我的手很潮。所以我在屏幕上放了 5 个字段,这取决于其他模型,我计算应该存在哪个字段,然后使用 ng-if ,从屏幕中删除其他人,剩下的人应该
  • 我想知道哪些特定字段未通过验证会很有帮助,可以对无法解决问题的字段进行自定义验证,但这对我来说真的很难到目前为止,从您的描述中可以看出。
  • 一个一个字段,每次我来到这个表格,它们一起形成一个代码,每个部分都可以称为另一个部分的父,但因为我不想创建很多表格,所以坚持我的验证方案,...所以第一个字段是活动的,其他填充零的字段是禁用的,而其他一些字段可能是不可见的...,下次第一个字段填充数据时,第二个是活动的,第三个用零填充,如果第三个是最后一个可见字段,那么在第三次我们进入表单时,第一个和第二个字段填充数据,第三个被激活。
  • 如果您根据自己的具体情况设置 plunkr,则更有可能获得答案。

标签: javascript angularjs validation angularjs-directive


【解决方案1】:

好的,这是您的代码所做的假设。当您检查验证时,您正在检查是否 value === false 否则您将其添加到您的表单中,这不是您要描述的逻辑。

您所说的是,如果该字段被禁用并设置为 0,则无论值如何,我都希望将其从表单中删除,然后如果值为 false,我希望将其从表单中删除,否则验证表单。只需进行逻辑检查以查看该字段是否已禁用并将其从验证中删除。

 if (value === 0) {
    form.$removeControl(control);
 } else if (value === false) {
    form.$addControl(control);
    angular.forEach(control.$error, function(validity, validationToken) {
        form.$setValidity(validationToken, !validity, control);
    });
 } else {
     form.$removeControl(control);
 }

【讨论】:

  • 首先,很抱歉给我造成的麻烦,因为我不是英语母语者。该部分由 5 个部分组成,取决于一些应该显示的条件,而其他部分不应该......那是我使用 ng-if 的时候,但这对我来说没问题。问题出在应该显示的组件上......它们再次由几个项目(启用的项目或禁用的项目)组成,我使用data-ng-disabled="condition"hs-disable-validation="condition"...当我使用hs-disable-validation它应该与验证系统对话,并告诉它不要观察这个元素。这就是我失败的地方
  • form.$removeControl(control) 即使在我的示例上运行良好,我的意思是它通过所有组件删除所有控件,然后再次添加控件以启用控件,但是一旦我检查整体验证,它说有错误,...一一他们都很好,但总的来说...没有
猜你喜欢
  • 2014-05-09
  • 1970-01-01
  • 2013-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
相关资源
最近更新 更多