Directive is not being called, Angularjs custom validator

Asked

Viewed 293 times

1

I have the following directive:

.directive('validateCPF', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {

            ctrl.$validators.cpf = function (modelValue, viewValue) {
                console.log('chamou directiva');
                var validatorCPF = new CPF();
                return (validatorCPF.valida(viewValue));
            };
        }
    };
});

This directive uses an external lib to validate the cpf, but it does not even reach the console.log.

My form:

<input id="cpf" class="col-xs-12 cpf" type="text" name="cpf" ng-model="cau.cpf" validate-CPF >

Angularjs version 1.4

1 answer

2


You have some errors in your directive statement. The AngularJS is applied by differentiating between uppercase and lowercase letters, and it is applied for each uppercase letter that you define in the .directive it should be lowercase and preceded by a hyphen in your HTML. Take the example:

//No angular
.directive('minhaDiretivaAqui', function () {

//E no seu html
<input minha-diretiva-aqui ...

Remembering that you should not start the name of .directive capital letter.


For your directive to work, you must declare so:

//AngularJS
.directive(validateCpf)

//No html
<input validate-cpf

The way you stated, you’d have to call her that way:

<input validate-c-p-f

Complementary to validation, you can call the function only after the user fills the CPF value through the ng-blur, so when the user finishes typing the CPF, it calls the function and does the check. See:

<input id="cpf" class="col-xs-12 cpf" type="text" name="cpf" ng-model="cau.cpf" validate-cpf ng-blur="verificaCpf(cau.cpf)">


//Na diretiva - Coloque a sua verificação dentro de uma função
scope.verificaCpf = function(valorCpf) {
    //Sua verificação aqui
    ctrl.$validators.cpf = ...
};
  • I liked the idea of Blur, but I will validate in the function in the directive if viewModel is defined. in this case only after losing focus, in the same way as with Blur...

  • A yes, at your discretion. I only mentioned it as an alternative. = D

Browser other questions tagged

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