自定义验证取决于另一个输入

时间:2015-12-22 13:46:13

标签: angularjs validation angularjs-directive

这个想法非常简单。我有两个输入,只有触及两个输入才能验证它们。至少有一个必须与0不同。我哪里错了?

HTML

<div class="form-group" ng-class="{'has-error' : (myForm.$submitted || myForm.for.$touched) && myForm.for.$invalid }">
    <label class="col-md-4 control-label" for="for">For</label>
    <div class="col-md-8">
        <input class="form-control" id="for" name="for" ng-model="item.for" ng-required="(some expression)" type="number" one-not-zero="item.against" one-not-zero-touched="myForm.against.$touched"/>
        <div ng-messages="myForm.for.$error" role="alert" ng-show="(myForm.$submitted || myForm.for.$touched) && myForm.for.$invalid">
            <div class="help-block" ng-message="required">
                REQUIRED
            </div>
            <div class="help-block" ng-message="oneNotZero">At least one has to be different than 0</div>
        </div>
    </div>
</div>

<div class="form-group" class="{'has-error' : (myForm.$submitted || myForm.against.$touched) && myForm.against.$invalid }">
    <label class="col-md-4 control-label" for="against">Against</label>
    <div class="col-md-8">
        <input class="form-control" id="against" name="against" ng-model="item.against" ng-required="(some expression) " type="number" one-not-zero="item.for" one-not-zero-touched="myForm.for.$touched"/>
        <div ng-messages="myForm.against.$error" role="alert" ng-show="(myForm.$submitted || myForm.against.$touched) && myForm.against.$invalid">
            <div class="help-block" ng-message="required">
                REQUIRED
            </div>
            <div class="help-block" ng-message="oneNotZero">At least one has to be different than 0</div>
        </div>
    </div>
</div>

指令

var oneNotZero = function() {
    return {
        restrict: "A",
        require: "ngModel",
        scope: {
            oneNotZero: "=",
            oneNotZeroTouched: "="
        },
        link: function(scope, element, attrs, ctrl) {
            ctrl.$validators.oneNotZero = function (modelValue, viewValue) {
                return scope.oneNotZeroTouched ? !((viewValue == 0) && (scope.oneNotZero == 0)) : true;
            };
        }
    };
};

myModule.directive("oneNotZero", oneNotZero);

编辑:我取得了一些进展,将代码更改为我的最新版本,但它并没有完全发挥作用。如果我没有对值进行任何更改,只需通过输入直到我进入提交按钮并按Enter键,验证就不会触发。我应该$watch输入的变化吗?

1 个答案:

答案 0 :(得分:0)

如果至少有一个字段不为0,则会提交表单。否则将显示错误消息。

<form name="myForm" novalidate>
    <input name="for" ng-model="item.for" type="number" required>
    <input name="against" ng-model="item.against" type="number" required>
    <input type="submit" value="Submit">

    <div ng-show="myForm.$submitted && (item.for == 0 || item.against == 0)">
        At leat one field must be different from 0.
    </div>
</form>