Search code examples
javascriptangularjsng-messages

Can I trigger ngMessages validation by hand?


I have an input field with a custom validator and ng-messages to show validation messages.

<input type="tel"
       ng-model="ctrl.phoneNumber"
       phone-number
       required />

The custom validator is simple:

ngModel.$validators.phoneNumber = () => {
    return $iElem.intlTelInput('isValidNumber');
};

For some other events I'd like to trigger validation by hand, also simple

$iElem.on('countrychange', () => {
    ngModel.$validate();
});

Which will trigger my custom validator and also this will validate the number again, the form.*.$error object will be updated too, but ngMessages won't reflect, the validation messages won't update somewhy :/

Any idea?

edit: when I go for the next input in the line ngMessages kicks in for that input AND for the phone-number input as well and the view gets updated, but it's late, like if it would omit one cycle to update the view


Solution

  • Since the countrychange event is not triggered by angular (i.e. outside the digest cycle) you'll need to wrap the validate call inside a $scope.$apply.

    iElem.on('countrychange', () => {
      $scope.$apply(function(){
        ngModel.$validate();
      })
    });
    

    See this discussion for an explanation