Angular js. Form validation

Home » Tutorials » JavaScript » Angular js. Form validation
In this tutorial we will consider form validation with angular. The main advantage of using angular to validate form is simplicity and fast implementation.
While making validation you need some important steps. First of all you need to add name attribute to form. After form will be available in $scope object. In fact form is instance of Form Controller. Next we must add name attribute to form input fields. After the will be available inside form object in $scope object. See image below.
Fields have got several important angular properties which use while form validation. Each of them can be true or false. See code example below.

Angular свойства полей

console.log("Содержимое поля валидно? " + $scope.addPlayerForm.pName.$valid);
console.log("Пользователь не взаимодействовал с полем? " + $scope.addPlayerForm.pName.$untouched);
console.log("Пользователь взаимодействовал с полем? " + $scope.addPlayerForm.pName.$touched);
console.log("Значение (содержимое) поля еще не менялось? " + $scope.addPlayerForm.pName.$pristine);
console.log("Значение (содержимое) поля менялось? " + $scope.addPlayerForm.pName.$dirty);
console.log("Содержимое поля не валидно? " + $scope.addPlayerForm.pName.$invalid);
Using these properties, we can validate our form. In our example we will check if fields are required. Approach is we will check propeties on boolean values. For example, we will add ng-disabled directive and it will act only when one of the field is not valid.

Code lesson

<!DOCTYPE html>
<html ng-app="playersApp">
    <head>
        <meta charset="utf-8">
        <title></title>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
        <style>
            /*input.ng-invalid-required {
                border: 1px solid red;
            }*/
        </style>
    </head>
    <body>

        <div class="container" ng-controller="playerCtrl">
            <div class="row">
                <div class="col-md-12">
                    <form class="form-horizontal" name="addPlayerForm" novalidate>
                        <legend>Список футболистов</legend>
                          <div class="form-group" ng-class="{'has-error': addPlayerForm.pName.$error.required && addPlayerForm.pName.$dirty}">
                            <label for="playerName" class="col-sm-4 control-label">Имя игрока</label>
                            <div class="col-sm-8">
                              <input type="text" required name="pName" ng-model="playerName" class="form-control" id="playerName" placeholder="Имя игрока">
                              <!--<span class="error" ng-show="addPlayerForm.pName.$invalid">Required!</span>-->
                              <span class="error" ng-show="addPlayerForm.pName.$dirty && addPlayerForm.pName.$error.required">Введите имя игрока!</span>
                            </div>
                          </div>
                          <div class="form-group">
                            <label for="playerTeam" class="col-sm-4 control-label">В какой команде играет</label>
                            <div class="col-sm-8">
                              <input type="text" name="pTeam" ng-model="playerTeam" class="form-control" id="playerTeam" placeholder="В какой команде играет">
                            </div>
                          </div>
                          <div class="form-group" ng-class="{'has-error': addPlayerForm.pCountry.$error.required && addPlayerForm.pCountry.$dirty}">
                            <label for="playerCountry" class="col-sm-4 control-label">Гражданство</label>
                            <div class="col-sm-8">
                                <input type="text" required name="pCountry" ng-model="playerCountry" class="form-control" id="playerCountry" placeholder="Гражданство">
                                <span class="error" ng-show="addPlayerForm.pCountry.$dirty && addPlayerForm.pCountry.$error.required">Игрок не может быть без гражданства!</span>
                            </div>
                          </div>
                          <div class="form-group">
                              <div class="col-sm-8 col-sm-offset-4">
                                  <button ng-disabled="addPlayerForm.pName.$invalid || addPlayerForm.pCountry.$invalid" ng-click="addPlayer(playerName, playerTeam, playerCountry)" class="btn btn-default">Добавить</button>
                              </div>
                          </div>
                    </form>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Игрок</th>
                                <th>Команда</th>
                                <th>Национальность</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr ng-repeat="player in players.playersObjects">
                                <td>{{player.name}}</td>
                                <td>{{player.team}}</td>
                                <td>{{player.country}}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <script src="angular.js"></script>
        <script>
            var app = angular.module("playersApp", []);

            var model = {
                playersObjects: []
            }

            app.controller("playerCtrl", function($scope){
                console.log($scope);
                $scope.players = model;
                $scope.addPlayer = function(playerName, playerTeam, playerCountry) {

                        $scope.players.playersObjects.push({name: playerName, team: playerTeam, country: playerCountry});
                        console.log("Содержимое поля валидно? " + $scope.addPlayerForm.pName.$valid);
                        console.log("Пользователь не взаимодействовал с полем? " + $scope.addPlayerForm.pName.$untouched);
                        console.log("Пользователь взаимодействовал с полем? " + $scope.addPlayerForm.pName.$touched);
                        console.log("Значение (содержимое) поля еще не менялось? " + $scope.addPlayerForm.pName.$pristine);
                        console.log("Значение (содержимое) поля менялось? " + $scope.addPlayerForm.pName.$dirty);
                        console.log("Содержимое поля не валидно? " + $scope.addPlayerForm.pName.$invalid);


                }
            });
        </script>

    </body>
</html>

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This