codememo

폼 제출 시 모든 폼 필드를 ng-touched로 프로그래밍 방식으로 설정

tipmemo 2023. 2. 16. 21:44
반응형

폼 제출 시 모든 폼 필드를 ng-touched로 프로그래밍 방식으로 설정

HTML:

<div class="form-group" 
     ng-class="{ 'has-error' : form.firstName.$invalid && form.firstName.$touched }">
  <label for="firstName" 
         class="control-label">
         First Name
  </label>
  <input type="text" 
         name="firstName" 
         id="firstName" 
         ng-model="editableUser.firstName" 
         class="form-control" 
         required>
  <span class="help-block" 
        ng-show="form.firstName.$error.required && form.firstName.$touched">
        First Name is required
  </span>
</div>

<input type="submit" 
       ng-click="submit()" 
       value="Submit" 
       class="btn btn-default">

사용자가 [Submit]를 클릭했을 때 비활성 필드에 대해 'has-error' 클래스를 시작하려고 합니다.

다음과 같은 일을 할 수 있다고 생각합니다.

$scope.submit = function () {
  if ($scope.form.$invalid) {
    angular.forEach($scope.form.$invalid, function(field) {
      field.$setTouched();
    });
    alert("Form is invalid.");
  }
};

하지만 없다.$setTouchedhttps://docs.angularjs.org/api/ng/type/form.FormController의 메서드

편집: 실현$setTouched존재합니다.https://docs.angularjs.org/api/ng/type/ngModel.NgModelController에 있습니다.

if ($scope.form.$invalid) {
    angular.forEach($scope.form.$error, function (field) {
        angular.forEach(field, function(errorField){
            errorField.$setTouched();
        })
    });
    alert("Form is invalid.");
}

plunker:http://plnkr.co/edit/XmvoTkIQ0yvFukrVSz11

최근에 추가된 $submitted를 사용해 보십시오.

<input type="text" 
     name="firstName" 
     id="firstName" 
     ng-model="editableUser.firstName" 
     class="form-control" 
     required>
   <span class="help-block" 
    ng-show="form.firstName.$error.required && (form.firstName.$touched || form.$submitted">
    First Name is required

Alexey의 답변에 따라 동일한 작업을 수행하는 새로운 메서드를 Form Controller에 추가할 수 있습니다.따라서, 송신 함수간에 코드를 카피할 필요가 없습니다.

// config.js
export default function config($provide) {
    $provide.decorator('formDirective', $delegate => {
        const fn = $delegate[0].controller.prototype
        if (!('$setTouched' in fn)) fn.$setTouched = function() {
            if (this.$invalid) {
                Object.values(this.$error).forEach(controls => {
                    controls.forEach(control => control.$setTouched())
                })
            }
        }
        return $delegate
    })
}
// controller.js
$scope.submit = function () {
    if ($scope.form.$invalid) {
        $scope.form.$setTouched();
        alert("Form is invalid.");
    }
};

왜 이런 검증을 하고 싶은지 궁금할 경우:iOS 제약조건 검증이 부족하기 때문에ng-submit유효하지 않은 형식에서도 호출됩니다.

위의 답변은 저에게 효과가 없었습니다.프로그램적으로 Touch를 True로 설정합니다.

예를 들어, 이 작업을 수행한 후에도$scope.frmUser["U_Name"].$setTouched(); $scope.frmUser["U_Name"].$invalid항상 진실했다.

송신 버튼은, 다음의 경우에만 유효하게 되어 있습니다.$scope.frmUser.$invalid거짓이다

대신 javascript에서 프로그램적으로 설정할 각 필드의 스코프 변수를 가져와서 true/false로 설정하면 문제가 없습니다.

uisng ES6 + lodash fp가 마음에 드신다면

import forEach from 'lodash/fp/forEach'

    validate()
    {
        forEach(forEach(field => field.$setTouched()))(this.form.$error)
    }

<form name="$ctrl.form">...</form>

다음은 현재 버전의 Angular에 대한 잘못된 답변입니다.으로 간단히 할 수 있다.

submit() {
    this.form.markAllAsTouched();
}

필드를 '터치'해야 하는 이유를 잘 모르겠습니다.일반적인 폼 검증을 사용합니다.필드를 실제 폼 요소로 감싸고 각도가 검증을 처리하도록 하면 됩니다.다음으로 작업 예를 제시하겠습니다.

$touched를 확인하거나 설정할 필요가 없습니다(특별한 이유가 없는 한). 필수 필드인 경우 입력 필드에 필수 속성을 사용합니다.

<input name="namefield" "text" ng-model="user.firstName" required/>

언급URL : https://stackoverflow.com/questions/30628611/programmatically-set-all-form-fields-to-ng-touched-on-form-submission

반응형