source

두 필드를 비교하는 사용자 정의 양식 유효성 검사 지시문

nicesource 2023. 2. 23. 22:54
반응형

두 필드를 비교하는 사용자 정의 양식 유효성 검사 지시문

난 각진 신입이고 각진 형태 검증 지침이 어떻게 작용하는지에 대해 고민하고 있어.

개별 필드에 지시문을 쉽게 추가할 수 있다는 것은 알지만, 두 양식 필드(둘 다 모델의 요소)를 비교하는 검증을 추가하려고 합니다.

다음은 폼 골격입니다.

<form name="edit_form" >
  <input name="min" type="number" ng-model="field.min"/>
  <input name="max" type="number" ng-model="field.max"/>
</form>

<div class="error" ng-show="edit_form.min.$dirty || edit_form.max.$dirty">
  <small class="error" ng-show="(what goes here?)">
    Min cannot exceed max
  </small>
</div>

즉, 지시문을 작성하여 표시/숨기기 위해 사용합니다.small.error한다면min그리고.max둘 다 가치가 있지만min > max1개의 디렉티브 내의 양쪽 필드에 액세스하려면 어떻게 해야 합니까?지시가 이 작업에 적합한 도구입니까?

지시는 필요 없습니다.max의 "min" 값을 min-value에 할당합니다.예를 들어 다음과 같습니다.

<input name="min" type="number" ng-model="field.min"/>
<input name="max" type="number" ng-model="field.max" min=" {{ field.min }}"/>

커스터마이즈도 필요 없습니다.
기타: 할 수 있다min=" {{ field.min + 1}}"

고양이 가죽을 벗기는 데는 여러 가지 방법이 있다.

PLUNKER

app.directive('lowerThan', [
  function() {

    var link = function($scope, $element, $attrs, ctrl) {

      var validate = function(viewValue) {
        var comparisonModel = $attrs.lowerThan;

        if(!viewValue || !comparisonModel){
          // It's valid because we have nothing to compare against
          ctrl.$setValidity('lowerThan', true);
        }

        // It's valid if model is lower than the model we're comparing against
        ctrl.$setValidity('lowerThan', parseInt(viewValue, 10) < parseInt(comparisonModel, 10) );
        return viewValue;
      };

      ctrl.$parsers.unshift(validate);
      ctrl.$formatters.push(validate);

      $attrs.$observe('lowerThan', function(comparisonModel){
        // Whenever the comparison model changes we'll re-validate
        return validate(ctrl.$viewValue);
      });

    };

    return {
      require: 'ngModel',
      link: link
    };

  }
]);

사용방법:

<input name="min" type="number" ng-model="field.min" lower-than="{{field.max}}" />
<span class="error" ng-show="form.min.$error.lowerThan">
  Min cannot exceed max.
</span>

간단한 비교가 어울릴까요?

<small class="error" ng-show="field.min > field.max">

이런 경우라면 과잉 살상이 될 것 같아요애플리케이션 로직을 포함한 뷰가 마음에 들지 않는 경우는, 컨트롤러의 기능으로 내보낼 수 있습니다.

$scope.isMinMaxInalid = function() {
    return $scope.field.min > $scope.field.max;
};

템플릿:

<small class="error" ng-show="isMinMaxInalid()">

저는 피드백 메시지 외에도 필드를 유효하지 않은 것으로 정의하여 제출을 방지해야 했습니다.그래서 @thewie 접근법과 같은 몇 가지 접근방식을 수집했습니다.뷰 구성을 통해 날짜 비교 솔루션을 수집했습니다.제시된 해결책을 종합할 수 있기를 바랍니다.

코드는 PLUNKER에 있다.

angular.module('MyApp')
    .directive('thisEarlierThan', function () {
        return {
            require: 'ngModel',
            restrict: 'A',
            link: function (scope, elem, attrs, ctrl) {
                var startDate,
                    endDate;

                scope.$watch(attrs.ngModel, function (newVal, oldVal, scope) {
                    startDate = newVal;
                    check();
                });

                scope.$watch(attrs.thisEarlierThan, function (newVal, oldVal, scope) {
                    endDate = newVal;
                    check();
                });

                var check = function () {
                    if (typeof startDate === 'undefined' || typeof endDate === 'undefined') {
                        return;
                    }

                    if (!validate(startDate)) {
                        startDate = new Date(startDate);
                        if (!validate(startDate)) {
                            return;
                        }
                    }

                    if (!validate(endDate)) {
                        endDate = new Date(endDate);
                        if (!validate(endDate)) {
                            return;
                        }
                    }

                    if (startDate < endDate) {
                        ctrl.$setValidity('thisEarlierThan', true);
                    }
                    else {
                        ctrl.$setValidity('thisEarlierThan', false);
                    }

                    return;
                };

                var validate = function (date) {
                    if (Object.prototype.toString.call(date) === '[object Date]') {
                        if (isNaN(date.getTime())) {
                            return false;
                        }
                        else {
                            return true;
                        }
                    }
                    else {
                      return false;
                    }
                };
            }
        };
    })
;

내 버전의 디렉티브:

module.directive('greaterThan', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attributes, ngModelController) {
            var otherValue;

            scope.$watch(attributes.greaterThan, function (value) {
                otherValue = value;

                ngModelController.$validate();
            });

            ngModelController.$parsers.unshift(function (viewValue) {
                ngModelController.$setValidity('greaterThan', !viewValue || !otherValue || viewValue > otherValue);

                return viewValue;
            });
        }
    };
});

https://github.com/nelsonomuto/angular-ui-form-validation 를 참조해 주세요.

그러면 범위와 해당 모델을 검증자 함수에 노출하는 API로 미리 구성된 지시문이 제공됩니다.

다음은 고객 고유의 사용 사례와 관련된 plunker입니다.http://plnkr.co/edit/S0rBlS?p=preview

디렉티브 검증자의 구문은 다음 예시와 같습니다. { errorMessage: 'Cannot contain the number one', validator: function (errorMessageElement, val, attr, element, model, modelCtrl){ /** * The model and modelCtrl(scope) are exposed in the validator function * */ return /1/.test(val) !== true;
} }

언급URL : https://stackoverflow.com/questions/20982751/custom-form-validation-directive-to-compare-two-fields

반응형