your programing

angularjs로 양식 유효성을 어떻게 확인합니까?

lovepro 2020. 10. 4. 12:53
반응형

angularjs로 양식 유효성을 어떻게 확인합니까?


저는 angularjs를 처음 접했습니다. 내 앱에 양식이 있다고 가정 해 보겠습니다. 인스펙터를 사용하여 angularjs가 폼이 유효하지 않다고 생각하면 ng-invalid 클래스를 폼에 추가한다는 것을 알았습니다. 아름다운.

따라서 양식이 유효한지 확인하려면 Jquery 선택기로 코드를 오염시켜야하는 것 같습니다. 양식 컨트롤러를 사용하지 않고 양식 유효성을 나타내는 angularjs 방법은 무엇입니까?


<form>ngApp 내부 태그 를 넣으면 AngularJS는 자동으로 양식 컨트롤러를 추가합니다 (실제로 form필수 동작을 추가 하는 지시문 이 있습니다). 이름 속성의 값은 범위에 바인딩됩니다. 그래서 다음과 같은 <form name="yourformname">...</form>것이 만족할 것입니다.

폼은 FormController의 인스턴스입니다. 양식 인스턴스는 선택적으로 name 속성을 사용하여 범위에 게시 할 수 있습니다.

따라서 양식 유효성을 확인하기 위해 $scope.yourformname.$valid범위 속성 값을 확인할 수 있습니다 .

양식에 대한 개발자 가이드 섹션 에서 더 많은 정보를 얻을 수 있습니다 .


<div ng-controller="ExampleController">
  <form name="myform">
   Name: <input type="text" ng-model="user.name" /><br>
   Email: <input type="email" ng-model="user.email" /><br>
  </form>
</div>

<script>
  angular.module('formExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

     //if form is not valid then return the form.
     if(!$scope.myform.$valid) {
       return;
     }
  }]);
</script>

당신은 또한 사용할 수 있습니다 myform.$invalid

if($scope.myform.$invalid){return;}

형태

  • FormController를 인스턴스화하는 지시문 모듈 ng 지시문.

name 속성이 지정되면 양식 컨트롤러가이 이름으로 현재 범위에 게시됩니다.

별칭 : ngForm

Angular에서는 양식을 중첩 할 수 있습니다. 이는 모든 하위 양식이 유효 할 때 외부 양식도 유효 함을 의미합니다. 그러나 브라우저는 요소의 중첩을 허용하지 않으므로 Angular는 동일하게 작동하지만 중첩 될 수있는 ngForm 지시문을 제공합니다. 이를 통해 중첩 된 양식을 가질 수 있으며, 이는 ngRepeat 지시문을 사용하여 동적으로 생성되는 양식에서 Angular 유효성 검사 지시문을 사용할 때 매우 유용합니다. 보간을 사용하여 입력 요소의 이름 속성을 동적으로 생성 할 수 없으므로 ngForm 지시문에서 각 반복 입력 집합을 래핑하고 외부 양식 요소에 중첩해야합니다.

CSS 클래스

양식이 유효한 경우 ng-valid 가 설정됩니다.

양식이 유효하지 않은 경우 ng-invalid 가 설정됩니다.

양식이 pristine이면 ng-pristine 이 설정됩니다.

양식이 더러 우면 ng-dirty 가 설정됩니다.

ng-submitted 는 양식이 제출 된 경우 설정됩니다.

ngAnimate는 추가 및 제거시 이러한 각 클래스를 감지 할 수 있습니다.

양식 제출 및 기본 조치 방지

클라이언트 측 Angular 애플리케이션에서 양식의 역할이 기존 왕복 앱과 다르기 때문에 브라우저가 양식 제출을 서버에 데이터를 보내는 전체 페이지 다시로드로 변환하지 않는 것이 바람직합니다. 대신 애플리케이션 별 방식으로 양식 제출을 처리하기 위해 일부 자바 스크립트 로직이 트리거되어야합니다.

이러한 이유로 Angular는 요소에 작업 속성이 지정되지 않은 경우 기본 작업 (서버에 대한 양식 제출)을 방지합니다.

You can use one of the following two ways to specify what javascript method should be called when a form is submitted:

ngSubmit directive on the form element

ngClick directive on the first button or input field of type submit (input[type=submit])

To prevent double execution of the handler, use only one of the ngSubmit or ngClick directives.

This is because of the following form submission rules in the HTML specification:

If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit) if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit if a form has one or more input fields and one or more buttons or input[type=submit] then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit] (ngClick) and a submit handler on the enclosing form (ngSubmit).

Any pending ngModelOptions changes will take place immediately when an enclosing form is submitted. Note that ngClick events will occur before the model is updated.

Use ngSubmit to have access to the updated model.

app.js:

angular.module('formExample', [])
  .controller('FormController', ['$scope', function($scope) {
    $scope.userType = 'guest';
  }]);

Form:

<form name="myForm" ng-controller="FormController" class="my-form">
  userType: <input name="input" ng-model="userType" required>
  <span class="error" ng-show="myForm.input.$error.required">Required!</span>
  userType = {{userType}}
  myForm.input.$valid = {{myForm.input.$valid}}
  myForm.input.$error = {{myForm.input.$error}}
  myForm.$valid = {{myForm.$valid}}
  myForm.$error.required = {{!!myForm.$error.required}}
 </form>

Source: AngularJS: API: form

참고URL : https://stackoverflow.com/questions/14299834/how-do-i-check-form-validity-with-angularjs

반응형