AngularJS formulärvalidering

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>

Prova själv

email

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>

Prova själv

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>

Prova själv

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 touched
  • ng-touched This field has been touched
  • ng-pristine This field has not been modified
  • ng-dirty This field has been modified
  • ng-valid Field content is valid
  • ng-invalid Field content is invalid
  • ng-valid-key Validate each key individually. 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 individually. 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 falseIf 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>

Prova själv

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>

Prova själv

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>

Prova själv

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 myDirectivemen 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 ngModeldet 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 myValidationdet 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>

Prova själv

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-showendast när användare eller e-post är $dirty och $invalid visas spans med färg: red.