AngularJS Formularvalidierung
- Vorherige Seite AngularJS-Formulare
- Nächste Seite AngularJS-API
AngularJS kann Eingabedaten validieren.
Formularvalidierung
AngularJS bietet client-seitige Formularvalidierung.
AngularJS überwacht den Status von Formularen und Eingabefeldern (input, textarea, select) und ermöglicht es Ihnen, den Benutzern den aktuellen Status zu benachrichtigen.
AngularJS enthält Informationen darüber, ob sie berührt oder geändert wurden.
Sie können Standard-HTML5-Attribute zur Validierung verwenden oder Ihre eigenen Validierungsfunktionen erstellen.
Client-seitige Validierung kann die Benutzer-Eingaben nicht alleine schützen. Server-seitige Validierung ist ebenfalls erforderlich.
erforderlich
Verwenden Sie HTML5-Attribute erforderlich
Der angegebene Wert muss ausgefüllt werden:
Beispiel
Dieses Eingabefeld ist obligatorisch:
<form name="myForm"> <input name="myInput" ng-model="myInput" required> </form> <p>The valid state of the input is:</p> <h1>{{myForm.myInput.$valid}}</h1>
Verwenden Sie den HTML5-Typ email
Der angegebene Wert muss eine E-Mail sein:
Beispiel
Dieser Eingabefeld muss eine E-Mail sein:
<form name="myForm"> <input name="myInput" ng-model="myInput" type="email"> </form> <p>The valid state of the input is:</p> <h1>{{myForm.myInput.$valid}}</h1>
Form state and input state
AngularJS continuously updates the state of forms and input fields.
The input field has the following states:
$untouched
This field has not been touched yet$touched
This field has been touched$pristine
This field has not been modified yet$dirty
This field has been modified$invalid
Field content is invalid$valid
Field content is valid
They are all properties of the input field, either true or false.
The form has the following states:
$pristine
No fields have been modified yet$dirty
One or more fields have been modified$invalid
Form content is invalid$valid
Form content is valid$subscribed
The form has been submitted
They are all properties of the form, which can be either true or false.
You can use these states to display meaningful messages to the user. For example, if a field is required and the user leaves it blank, a warning should be issued to the user:
Beispiel
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>
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
This field has not been touched yetng-touched
This field has been touchedng-pristine
This field has not been modified yetng-dirty
This field has been modifiedng-valid
Field content is validng-invalid
Field content is invalidng-valid-key
Validate each key individually. For example:ng-valid-required
This 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 yetng-dirty
One or more fields have been modifiedng-valid
Form content is validng-invalid
Form content is invalidng-valid-key
Validate each key individually. For example:ng-valid-required
This 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 false
Then these classes will be removed.
Please add styles to these classes to provide a better and more intuitive user interface for your application.
Beispiel
Apply standard CSS styles:
<style> input.ng-invalid { background-color: pink; }; input.ng-valid { background-color: lightgreen; }; </style>
You can also set the form style.
Beispiel
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>
Benutzerdefinierte Validierung
Eine eigene Validierungsfunktion zu erstellen erfordert einige Tricks; Sie müssen eine neue Anweisung zu der Anwendung hinzufügen und einige spezifische Parameter für die Validierung in der Funktion innerhalb des Anweisungscodes verwenden.
Beispiel
Erstellen Sie Ihre eigene Anweisung, die eine benutzerdefinierte Validierungsfunktion enthält und verwenden Sie my-directive
Verwenden Sie es.
Das Feld ist nur gültig, wenn der Wert den Buchstaben "e" enthält:
<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>Beispiel Erklärung:
In HTML wird die neue Anweisung durch Verwendung des Attributes my-directive
bezeichnet.
In JavaScript fügen wir zunächst eine als myDirective
neue Anweisung.
Denken Sie daran, dass Sie bei der Benennung einer Anweisung den CamelCase-Namen verwenden müssen, wie myDirective
aber wenn Sie es aufrufen, müssen Sie den Namen mit Bindestrichen trennen, wie my-directive
.
Dann geben Sie ein Objekt zurück, in dem Sie angeben, dass wir ngModel
, das ist ngModelController
.
Erstellen Sie eine Verknüpfungsfunction, die einige Parameter annimmt, darunter der vierte Parameter mCtrl
ist ngModelController
.
Dann spezifizieren Sie eine Funktion, im Beispiel myValidation
es akzeptiert einen Parameter, der den Wert des Eingabeelements ist.
Testen Sie, ob der Wert den Buchstaben "e" enthält und stellen Sie die Gültigkeit des Modellcontrollers ein, true
oder false
.
Letztendlich,mCtrl.$parsers.push(myValidation);
wird myValidation
Funktionen zu einem Array anderer Funktionen hinzufügen, die bei jeder Änderung des Eingabewerts ausgeführt werden.
验证示例
<!DOCTYPE html> <html> <script src="https://cdn.staticfile.net/angular.js/1.6.9/angular.min.js"></script> <body> <h2>验证示例</h2> <form ng-app="myApp" ng-controller="validateCtrl" name="myForm" novalidate> <p>用户名:<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">用户名是必填项。< </span> </p> <p>电子邮件:<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">电子邮件是必填项。</span> <span ng-show="myForm.email.$error.email">无效的电子邮件地址。</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>
HTML-Formularattribut novalidate Wird verwendet, um die Standardbrowser-Validierung zu deaktivieren.
Beispiel erläutert:
AngularJS- Anweisungen ng-model
Binden Sie das Eingabelement an das Modell.
Das Modellobjekt hat zwei Eigenschaften:user
und email
.
aufgrund ng-show
nur, wenn user oder email $dirty
und $invalid
wird angezeigt, wenn spans mit color:red enthalten sind.
- Vorherige Seite AngularJS-Formulare
- Nächste Seite AngularJS-API