Validate input size with Angularjs

Asked

Viewed 1,120 times

3

I have a field in a form that I need to validate with angular. The field should have up to 11 characters. If you have less than 5 should be displayed an error message requiring the user a correct numbering.

Angular Controller

angular.module('xxx') .controller('yyyController', function ($scope) {
    var vm = $scope;      
    vm.validarCPF = function(){

      if( condicao < 11){
       //mensagem de erro
      }

    };

HTML code

<input type="text" name="cpf" id="cpf" ng-model="cpfusuario">

1 answer

7


You can use the directives ng-minlength and ng-maxlength straight into HTML as below:

<div ng-controller="ExampleController">
  <form name="meuForm">
    <label>
       User name:
       <input type="text" name="cpf" id="cpf" ng-model="cpfusuario" ng-minlength="5" ng-maxlength="11" maxlength="11">
    </label>
    <div role="alert">
      <span class="error" ng-show="meuForm.cpf.$error.minlength">
        Tamanho mínimo de 5!</span>
      <span class="error" ng-show="meuForm.cpf.$error.maxlength">
        Tamanho máximo de 11!</span>
    </div>
  </form>
</div>

See more in the Angularjs documentation: https://docs.angularjs.org/api/ng/directive/input

  • But what about the error message ? How to ask the user for a correct numbering ?

  • And how to validate this in the controller ?? I don’t want to leave the html full of ng-s...

  • I have to do the validation on the controller...

  • The idea of using Angularjs is exactly to decrease javascript code. as for the message, this '<div role="Alert">' is responsible for displaying the message to the user. Remembering that this use of directives and HTML code instead of filling our javascript is one of the differentials of Angularjs and the use of HTML5.

Browser other questions tagged

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