I ran into a problem that I cannot solve. I have several inputs with each directive to check the input value, for example:
<div class="row form-group"> <div class="col-sm-6">last name</div> <div class="col-sm-6"> <div class="input-group" ng-class="{'has-error': form.lastname.$invalid && (form.lastname.$touched || form.$submitted)}"> <input type="text" name="lastname" class="form-control" model-blur validator-lastname ng-trim="true" ng-model="fields.lastname.value" ng-maxlength="fields.lastname.validation.maxLength"> <input-group-addon class="input-group-addon" iga-char="" iga-form="form" iga-field="form.lastname" iga-if-touched="true"> </input-group-addon> </div> <form-message-list fml-form="form" fml-field="form.lastname" fml-label="Last name" fml-fieldData="fields.lastname"> </form-message-list> </div> </div>
The following pattern is required in this field: /^[\'a-zA-Z_]+( [\'a-zA-Z_]+)*$/
My problem is this: When I add an invalid value for my input, for example: /, my invalid message remains and ng-invalid-pattern remains in my field.
When I add this pattern to my field as follows: ng-pattern="/^[\'a-zA-Z_]+( [\'a-zA-Z_]+)*$/" I have no problem. But when I try to validate with my validator-lastname directive , it only validates once. When I fill the input with an invalid value and then change it to empty, which is allowed, the ng-invalid-pattern error persists.
This is my directive:
angular.module('app') .directive('validatorLastname', validatorLastname); function validatorLastname() { var directive = { require: 'ngModel', link: link }; return directive; function link(scope, element, attrs, modelCtrl) { var valid = false; var formatter = function (inputValue) { if (inputValue) { var res = inputValue.match(/^[\'a-zA-Z_]+( [\'a-zA-Z_]+)*$/); if (res && res.length > 0) { valid = true; } modelCtrl.$setValidity('pattern', valid); valid = false; } return inputValue; }; modelCtrl.$parsers.push(formatter); if (scope[attrs.ngModel] && scope[attrs.ngModel] !== '') { formatter(scope[attrs.ngModel]); } } }
I created a JSFiddle to reproduce the problem: http://jsfiddle.net/sZZEt/537/
Hope someone can point me in the right direction. Thanks in advance.
javascript angularjs angularjs-directive
Matheno
source share