AngularJS formulärvalidering
- Föregående sida AngularJS Formulär
- Nästa sida AngularJS API
AngularJS kan validera inputdata.
Formulärvalidering
AngularJS erbjuder klientformulärvalidering.
AngularJS övervakar formulär och inmatningsfält (input, textarea, select) status och tillåter dig att informera användaren om den aktuella statusen.
AngularJS innehåller information om om de har berörts eller ändrats.
Du kan använda standard HTML5-attribut för att validera input, eller skapa din egen valideringsfunktion.
Klientverifiering kan inte ensam skydda användarinput. Serververifiering är också nödvändig.
obligatorisk
Använd HTML5-attribut obligatorisk
Det specificerade fältet måste fyllas i:
exempel
Detta inmatningsfält är obligatoriskt:
<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>
Använd HTML5-typ email
Det specificerade värdet måste vara ett e-postmeddelande:
exempel
Detta inmatningsfält måste vara ett e-postmeddelande:
<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 the form and input fields.
The input field has the following states:
$untouched
This field has not been touched$touched
This field has been touched$pristine
This field has not been modified$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
The form content is invalid$valid
The 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:
exempel
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 form 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 touchedng-touched
This field has been touchedng-pristine
This field has not been modifiedng-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
The form content is validng-invalid
The 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
If not, these classes will be removed.
Please add styles to these classes to provide a better and more intuitive user interface for your application.
exempel
Apply standard CSS styles:
<style> input.ng-invalid { background-color: pink; }; input.ng-valid { background-color: lightgreen; }; </style>
You can also set the form's style.
exempel
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>
Anpassad validering
För att skapa en egen valideringsfunktion krävs det några färdigheter; du måste lägga till ett nytt direktiv till applikationen och använda vissa specifika parametrar för att behandla valideringen inom funktionen.
exempel
Skapa ditt eget direktiv som innehåller en anpassad valideringsfunktion och använd my-directive
referera till det.
Fältet är endast giltigt om det innehåller tecknet "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 { kräver: 'ngModel', länk: function(scope, element, attr, mCtrl) { function myValidation(value) { om (value.indexOf("e") > -1) { mCtrl.$setValidity('charE', true); } annars { mCtrl.$setValidity('charE', false); }; returnera värdet; }; mCtrl.$parsers.push(myValidation); }; }; }); </script>Exempel förklarat:
I HTML kommer det nya direktivet att användas genom att använda attribut my-directive
för att referera till.
I JavaScript lägger vi till en variabel myDirective
nytt direktiv.
Kom ihåg att när du namnger en direktiv måste du använda huvudbokstavssystem, som myDirective
men när du anropar den måste du använda namn med bindestreck, som my-directive
.
Sedan returnera ett objekt där vi specificerar vad vi behöver ngModel
det vill säga ngModelController
.
Skapa en länkfunktion som tar emot några parametrar, där den fjärde parametern mCtrl
är ngModelController
.
Sedan specificera en funktion, i detta fall myValidation
det tar emot en parameter, som är värdet för inmatningselementet.
Testa om värdet innehåller bokstaven "e" och sätt modellkontrollernas giltighet till true
eller false
.
Till slut,mCtrl.$parsers.push(myValidation);
kommer att myValidation
Funktioner läggs till i en array av andra funktioner, som kommer att köras vid varje ändring av inmatningsvärde.
Valideringsexempel
<!DOCTYPE html> <html> <script src="https://cdn.staticfile.net/angular.js/1.6.9/angular.min.js"></script> <body> <h2>Valideringsexempel</h2> <form ng-app="myApp" ng-controller="validateCtrl" name="myForm" novalidate> <p>Användarnamn:<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">Användarnamn är ett obligatoriskt fält.< </span> </p> <p>E-post:<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">E-post är ett obligatoriskt fält.</span> <span ng-show="myForm.email.$error.email">Invalid e-postadress.</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-formulärattribut novalidate Används för att inaktivera standardbrowsrervalidering.
Exempel på förklaring:
AngularJS Direktiv ng-model
Bind inmatningselementet till modellen.
Modellobjekt har två egenskaper:user
och email
.
på grund av ng-show
endast när användare eller e-post är $dirty
och $invalid
visas spans med färg: red.
- Föregående sida AngularJS Formulär
- Nästa sida AngularJS API