Search code examples
angularvalidation

Angular Custom Validation using Directive not working properly in ng- change


I have a custom validator using directives. im displaying validation using a method called by ng-change. Validation displays only in second change.

  <textarea id="txtEmail" name="emailId" type="text" class="form-control" 
           ng-change="$ctrl.validateForm()" ng-model-options="{allowInvalid: true}" 
           validate-Email="$ctrl.emailId" 
           ng-model="$ctrl.emailId" disabled-exception aria-labelledby="Email">
  </textarea>

Here validate-Email is the directive which use regex to validate email.

For ex: test@gmail.co , in this case if i remove last character 'o' , it will not display error validation. but if i remove last two character 'co' it will display proper validation.

validateForm method is like

         ` vm.validateForm = function () {
                var errors = [];
                angular.forEach(vm.form.$error, function (item, key: string) {
                angular.forEach(item, function (errorField) {
                                    errors.push("Email Error");
                }`

Expecting solution to display validation properly.


Solution

  • First write a function like

    vm.validate = function () {
        $timeout.cancel(callValidation);
        callValidation = $timeout(vm.validateForm, 1000);
    
    }
    

    then call the "vm.validate" function in textarea instead of "vm.validateForm".

    I hope this will slove your query.