Walidacja formularza AngularJS

AngularJS może walidować dane wejściowe.

Walidacja formularza

AngularJS oferuje walidację formularzy klienta.

AngularJS monitoruje stan formularzy i pól wejściowych (input, textarea, select) i pozwala powiadomić użytkownika o bieżącym stanie.

AngularJS zawiera również informacje, czy dane zostały dotknięte lub zmodyfikowane.

Możesz użyć standardowych atrybutów HTML5 do walidacji wejścia, a także utworzyć własną funkcję walidacji.

Klient验证不能单独保护用户输入。服务器端验证也是必要的。

required

Użyj atrybutów HTML5 required Podany musi być wypełniony polem wejściowym:

przykład

To pole wejściowe jest wymagane:

<form name="myForm">  
  <input name="myInput" ng-model="myInput" required>  
</form>  
<p>The valid status of the input is:</p>  
<h1>{{myForm.myInput.$valid}}</h1>

Spróbuj sam

email

Użyj typu HTML5 email Podany wartość musi być adresem e-mail:

przykład

To pole wejściowe musi być adresem e-mail:

<form name="myForm">  
  <input name="myInput" ng-model="myInput" type="email">  
</form>  
<p>The valid status of the input is:</p>  
<h1>{{myForm.myInput.$valid}}</h1>

Spróbuj sam

Form state and input state

AngularJS continuously updates the state of forms and input fields.

The input field has the following status:

  • $untouched The field has not been touched
  • $touched The field has been touched
  • $pristine The field has not been modified yet
  • $dirty The field has been modified
  • $invalid Field content is invalid
  • $valid Field content is valid

They are all input field properties and can be either true or false.

The form has the following status:

  • $pristine No fields have been modified yet
  • $dirty One or more fields have been modified
  • $invalid The form content is invalid
  • $valid The form content is valid
  • $subscribed The form has been submitted

They are all form properties and can be either true or false.

You can use these states to display meaningful messages to users. For example, if a field is required and the user leaves it blank, a warning should be issued to the user:

przykład

If the field has been touched and is empty, display an error message:

<input name="myName" ng-model="myName" required>  
<span ng-show="myForm.myName.$touched && myForm.myName.$invalid">The name is a required field.</span>

Spróbuj sam

CSS classes

AngularJS adds CSS classes to forms and input fields based on their state.

The following classes have been added to or removed from the input field:

  • ng-untouched The field has not been touched
  • ng-touched The field has been touched
  • ng-pristine The field has not been modified yet
  • ng-dirty The field has been modified
  • ng-valid Field content is valid
  • ng-invalid Field content is invalid
  • ng-valid-key Validate each key every time. For example:ng-valid-requiredThis is very useful when there are multiple required validations.
  • ng-invalid-key For example:ng-invalid-required

The following classes have been added to or removed from the form:

  • ng-pristine No fields have been modified yet
  • ng-dirty One or more fields have been modified
  • ng-valid The form content is valid
  • ng-invalid The form content is invalid
  • ng-valid-key Validate each key every time. For example:ng-valid-requiredThis is very useful when there are multiple required validations.
  • ng-invalid-key For example:ng-invalid-required

If the value represented by the class is falseThen these classes will be removed.

Please add styles to these classes to provide a better, more intuitive user interface for your application.

przykład

Apply standard CSS styles:

<style>
input.ng-invalid {
  background-color: pink;
};
input.ng-valid {
  background-color: lightgreen;
};
</style>

Spróbuj sam

You can also set the form style.

przykład

Apply styles to both the unmodified (original) form and the modified form:

<style>
form.ng-pristine {
  background-color: lightblue;
};
form.ng-dirty {
  background-color: pink;
};
</style>

Spróbuj sam

Niestandardowa walidacja

Tworzenie własnej funkcji walidacji wymaga pewnych umiejętności; musisz dodać nową instrukcję do aplikacji i użyć pewnych określonych parametrów do przetwarzania walidacji wewnątrz funkcji.

przykład

Utwórz własną instrukcję, która zawiera niestandardową funkcję walidacji i użyj jej my-directive odnosi się do niej.

Pole jest poprawne tylko gdy wartość zawiera znak "e":

<form name="myForm">
<input name="myInput" ng-model="myInput" required my-directive>
</form>
<script>
var app = angular.module('myApp', []);
app.directive('myDirective', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attr, mCtrl) {
      function myValidation(value) {
        if (value.indexOf("e") > -1) {
          mCtrl.$setValidity('charE', true);
        } else {
          mCtrl.$setValidity('charE', false);
        };
        return value;
      };
      mCtrl.$parsers.push(myValidation);
    };
  };
});
</script>

Spróbuj sam

Przykład wyjaśniony:

W HTML, nowa instrukcja zostanie użyta poprzez użycie atrybutu my-directive aby odwołać się do niej.

W JavaScript, najpierw dodaj nazwę myDirective nowej instrukcji.

Pamiętaj, że gdy nazywasz instrukcję, musisz używać camelCase, np. myDirectiveale gdy go wywołujesz, musisz użyć nazwy rozdzielonej myślnikami, np. my-directive.

Następnie zwróć obiekt, w którym zdefiniujemy, co mamy ngModelczyli ngModelController.

Utwórz funkcję łączącą, która przyjmuje kilka parametrów, w tym czwarty parametr mCtrl jest ngModelController.

Następnie zdefiniuj funkcję, w tym przypadku o nazwie myValidationOn przyjmuje jeden parametr, który jest wartością elementu wejściowego.

Testuj, czy wartość zawiera literę "e" i ustaw wartość walidacji kontrolera modelu na true lub false.

Ostatecznie,mCtrl.$parsers.push(myValidation); będzie myValidation Funkcja dodana do tablicy innych funkcji, które będą wykonywane przy każdym zmianie wartości wejścia.

Przykład walidacji

<!DOCTYPE html>
<html>
<script src="https://cdn.staticfile.net/angular.js/1.6.9/angular.min.js"></script>
<body>
<h2>Przykład walidacji</h2>
<form ng-app="myApp"  ng-controller="validateCtrl"
name="myForm" novalidate>
<p>Nazwa użytkownika:<br>
  <input type="text" name="user" ng-model="user" required>
  <span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
  <span ng-show="myForm.user.$error.required">Nazwa użytkownika jest obowiązkowa。<
  </span>
</p>
<p>Adres e-mail:<br>
  <input type="email" name="email" ng-model="email" required>
  <span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
  <span ng-show="myForm.email.$error.required">Adres e-mail jest obowiązkowy.</span>
  <span ng-show="myForm.email.$error.email">Niepoprawny adres e-mail.</span>
  </span>
</p>
<p>
  <input type="submit"
  ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
  myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {}}
  $scope.user = 'Bill Gates';
  $scope.email = 'bill.gates@gmail.com';
});
</script>
</body>
</html>

Spróbuj sam

Atrybuty formularza HTML novalidate Używane do wyłączenia domyślnej walidacji przeglądarki.

Przykład wyjaśnienia:

Instrukcje AngularJS ng-model Przypisz element wejściowy do modelu.

Obiekt modelu ma dwie właściwości:user i email.

z powodu ng-showtylko gdy user lub email jest $dirty i $invalid Tylko, gdy span ma kolor: czerwony, będzie się wyświetlał.