AngularJS formuliervalidatie

AngularJS kan invoergegevens valideren.

Formuliervalidatie

AngularJS biedt client-side formuliervalidatie.

AngularJS monitort de status van formulieren en invoervelden (input, textarea, select) en laat u gebruikers de huidige status mededelen.

AngularJS bevat ook informatie over of ze zijn aangetikt of gewijzigd.

U kunt standaard HTML5 eigenschappen gebruiken om invoer te valideren, of u kunt uw eigen validatiefunctie maken.

Client-side validatie kan de gebruikersinvoer niet alleen beschermen. Server-side validatie is ook nodig.

vereist

Gebruik HTML5 eigenschappen vereist Deze invoerveld moet worden ingevuld:

voorbeeld

Dit invoerveld is vereist:

<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>

Probeer het zelf uit

email

Gebruik HTML5 type email Deze waarde moet een e-mailadres zijn:

voorbeeld

Dit invoerveld moet een e-mailadres zijn:

<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>

Probeer het zelf uit

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
  • $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 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 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:

voorbeeld

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>

Probeer het zelf uit

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
  • ng-touched This field has been touched
  • ng-pristine This field has not been modified yet
  • 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 every time. For example:ng-valid-requiredIt 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-requiredIt 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 and more intuitive user interface for your application.

voorbeeld

Apply standard CSS styles:

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

Probeer het zelf uit

You can also set the form's style.

voorbeeld

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>

Probeer het zelf uit

Aangepaste validatie

Het maken van een aangepaste validatiefunctie vereist enige vaardigheid; je moet een nieuwe instructie toevoegen aan de applicatie en enkele specifieke parameters gebruiken om de validatie binnen de functie te verwerken.

voorbeeld

Maak je eigen instructie, bevat een aangepaste validatiefunctie en gebruik my-directive het verwijzen naar het.

Het veld is alleen geldig wanneer de waarde de letter "e" bevat:

<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>

Probeer het zelf uit

Example Explained:

In HTML, wordt de nieuwe instructie weergegeven door gebruik te maken van het attribuut my-directive om te verwijzen.

In JavaScript, voegen we eerst een genaamd myDirective nieuwe instructie.

Onthoud, wanneer je een instructie naamgeeft, moet je het camelCase-notatie gebruiken, zoals myDirectivemaar wanneer je het aanroept, moet je de naam met een koppelteken gebruiken, zoals my-directive.

Vervolgens, retourneer een object waarin we specificeren dat we ngModeldus ngModelController.

Maak een koppelfunctie, die enkele parameters accepteert, waarvan de vierde parameter mCtrl is ngModelController.

Specificeer vervolgens een functie, in dit voorbeeld genaamd myValidationhet accepteert een parameter, de waarde van het invoerelement.

Test of de waarde de letter "e" bevat en stel de geldigheid van de modelcontroller in als true of false.

Ten slotte,mCtrl.$parsers.push(myValidation); zal myValidation Functies toevoegen aan een array van andere functies, die elke keer worden uitgevoerd wanneer de waarde van de invoer verandert.

Validatievoorbeeld

<!DOCTYPE html>
<html>
<script src="https://cdn.staticfile.net/angular.js/1.6.9/angular.min.js"></script>
<body>
<h2>Validatievoorbeeld</h2>
<form ng-app="myApp"  ng-controller="validateCtrl"
name="myForm" novalidate>
<p>Gebruikersnaam:<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">Gebruikersnaam is verplicht.<
  </span>
</p>
<p>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">E-mail is verplicht.</span>
  <span ng-show="myForm.email.$error.email">Ongeldige e-mailadres.</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>

Probeer het zelf uit

HTML formulier eigenschappen novalidate gebruikt om de standaard browservalidatie uit te schakelen.

Voorbeeld uitleg:

AngularJS Directieven ng-model bind de invoerelementen aan het model.

het modelobject heeft twee eigenschappen:user en email.

vanwege ng-showalleen wanneer user of email $dirty en $invalid toont spans met de kleur color:red.