Form validation - Angularjs

Asked

Viewed 1,242 times

1

I am trying to validate a simple form, where when the user leaves some field blank a div is damaged with this error. Follow the code

var playlistApp = angular.module('playlistApp', []);

playlistApp.controller("LucasCtrl", ['$scope', function($scope) {

  var vm = this;
  vm.IsErrorNome = false;

  $scope.validarCampos = function() {
    if ($scope.nome == null) {
      vm.IsErrorNome = true;
      return;
    }
  }

}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<body ng-app="playlistApp" ng-controller="LucasCtrl">
  <div class="container">
    <div class="row">
      <div class="col-md-6">
        <div class="form">
          Nome:
          <input type="text" class="form-control" ng-model="nome">
          <div ng-show="IsErrorNome">Nome em branco</div>
          Idade:
          <input type="number" class="form-control" ng-model="idade"> Endereço:
          <input type="text" class="form-control" ng-model="endereco"> Telefone de contato:
          <input type="text" class="form-control" ng-model="endereco">
          <br>
          <input type="submit" ng-click="validarCampos()" value="Próximo >" class="btn btn-success pull-right">
        </div>
      </div>
    </div>
  </div>
</body>

However, the div does not appear when clicking on Ubmit, I debugged by Chrome and saw that the states are being changed... Can anyone help me? Thanks

1 answer

1

The example below works with the element form to manage content validations.

Note that it receives a name, userForm. This is important because the Angular tando adds a mention to the form to the scope of the controller how many features to check the cause of validation errors.

Each control also has its own property name filled. In the example I used the same name used in ng-model.

You can then use:
- [nomeDoFormulario].[nomeDoCampo].$valid- to determine whether that field is valid;
- [nomeDoFormulario].[nomeDoCampo].$error - to access the field validation error justification.
- [nomeDoFormulario].$valid - to verify that the form has no other validation error.

var playlistApp = angular.module('playlistApp', []);

playlistApp.controller("LucasCtrl", ['$scope', function($scope) {

  $scope.validarCampos = function() {
  	if ($scope.userForm.$valid) {
		alert('Seu formulário está corretamente preenchido.');
  			}
  }
}]);
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  
  <body ng-app="playlistApp" ng-controller="LucasCtrl">
    <div class="container">
      <div class="row">
        <div class="col-md-6">
        <form name="userForm" ng-submit="validarCampos()" novalidate class="form">
            <table>
              <tr>
                <td class="border-bottom" ng-class="{'border-success': userForm.nome.$valid, 'border-warning': userForm.nome.$invalid}">
                  Nome
                </td>
                <td><input type="text" class="form-control" name="nome" ng-model="nome" required></td>
              </tr>
              <tr>
                <td class="border-bottom" ng-class="{'border-success': userForm.idade.$valid, 'border-warning': userForm.idade.$invalid}">
                  Idade
                </td>
                <td><input type="number" class="form-control" name="idade" ng-model="idade" min="18"></td>
              </tr>
              <tr>
                <td class="border-bottom" ng-class="{'border-success': userForm.endereco.$valid, 'border-warning': userForm.endereco.$invalid }">
                  Endereço
                </td>
                <td><input type="text" class="form-control" name="endereco" ng-model="endereco" ng-minlength="3"></td>
              </tr>
              <tr>
                <td class="border-bottom" ng-class="{'border-success': userForm.telefone.$valid, 'border-warning': userForm.telefone.$invalid }">
                  Telefone de contato
                </td>
                <td><input type="text" class="form-control" name="telefone" ng-model="telefone"></td>
              </tr>
              <tr>
                <td colspan=2><input type="submit" value="Próximo >" class="btn btn-success pull-right" ng-disabled="!userForm.$valid"/></td>
              </tr>
            <table>

            <div ng-show="userForm.nome.$error.required">O campo nome é mandatório.</div>
            <div ng-show="userForm.idade.$error.min">Se informada, a idade deve ser maior ou igual a 18 anos.</div>
            <div ng-show="userForm.endereco.$error.minlength">Se informado, o endereço deve possuir no mínimo 20 caracteres.</div>

            </form>
          </div>
        </div>
      </div>
    </div>
  </body>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.