Catch validation error in controller thrown by own directives


#1

Hello I want to catch validation error in my controller.

My html looks like this:

<div class="col-50">
  <input type="tel" name="phoneNumber" ng-model="appointmentForm.phoneNumber" ng-pattern="/^\+?\d{6,15}$/">
  <div role="alert">
    <span class="error" ng-if="submitted && form.phoneNumber.$error.pattern" >
      Vul een geldige telefoon
    </span>
  </div>
</div>

So how can I catch the error on controller side? I tried to use

$scope.form.phoneNumber.$error

to get access to the errors but its not working.

Is there a good way to check if the full form has some errors?


#2

No one got an idea, or is the question not clear?


#3

should do the following:

controller:
$scope.form = {};

template:

<form name="form.myForm">
   <input type="tel" name="phoneNumber" ng-model="appointmentForm.phoneNumber" ng-pattern="/^\+?\d{6,15}$/">
</form>

now you should be able to access your form in the controller via $scope.form.myForm …
There you can check if $scope.form.myForm.phoneNumber is valid or the whole form is valid and so on.


#4

Well the input tags are in a form and I get access to the phoneNumber via $scope.form.myForm.phoneNumber. But how do I check if its valid or not?


#5

keep in mind the model and the name on the form are two different things.
on the model the value is stored.

on myForm.inputName -> you have additional information like myForm.inputName.$valid|invalid
https://docs.angularjs.org/api/ng/directive/input