Angularjs ui-mask with ng-sample

below code does not work.

<input type="text" class="form-control input-sm" placeholder="hh:mm:ss" name="hhmmss" ng-model="data.hhmmss" ui-mask="99:99:99" ng-pattern="/^([0-2]|0[0-9]|1[0-9]|2[0-3]):?[0-5][0-9]:?[0-5][0-9]$/" /> 

when the input value is 20:00:00 , then formName.hhmmss.$error.pattern is true .

if you remove ui-mask :

 <input type="text" class="form-control input-sm" placeholder="hh:mm:ss" name="hhmmss" ng-model="data.hhmmss" ng-pattern="/^([0-2]|0[0-9]|1[0-9]|2[0-3]):?[0-5][0-9]:?[0-5][0-9]$/" /> 

when the input value is 20:00:00 , then formName.hhmmss.$error.pattern is false .

How to use regex in ng-pattern ?

+5
source share
2 answers

I had the same problem and changed the mask.js file to update the value of the area on the keyboard. There is a line of code that does this, but is not executed all the time.

 controller.$setViewValue(valUnmasked); 

Update the if statement as follows:

 if (valAltered || iAttrs.ngPattern) { 

This will launch "scope.apply" when you click and update the model.

+1
source

Angular 1.3.19 changed the behavior of ng-pattern , which violates u-mask.

Currently, the ng-pattern directive checks $viewValue instead of $modelValue - Link in the list of changes .

Command

Angular provided a custom directive that returns the previous behavior. This is a good problem to solve this problem.

You must add the pattern-model attribute to the fields when using both ui-mask and ng-pattern .

 <input type="text" class="form-control input-sm" placeholder="hh:mm:ss" name="hhmmss" ng-model="data.hhmmss" ng-pattern="/^([0-2]|0[0-9]|1[0-9]|2[0-3]):?[0-5][0-9]:?[0-5][0-9]$/" ui-mask="99:99:99" pattern-model /> 

Directive code (add it to your code base):

 .directive('patternModel', function patternModelOverwriteDirective() { return { restrict: 'A', require: '?ngModel', priority: 1, compile: function() { var regexp, patternExp; return { pre: function(scope, elm, attr, ctrl) { if (!ctrl) return; attr.$observe('pattern', function(regex) { /** * The built-in directive will call our overwritten validator * (see below). We just need to update the regex. * The preLink fn guarantees our observer is called first. */ if (angular.isString(regex) && regex.length > 0) { regex = new RegExp('^' + regex + '$'); } if (regex && !regex.test) { //The built-in validator will throw at this point return; } regexp = regex || undefined; }); }, post: function(scope, elm, attr, ctrl) { if (!ctrl) return; regexp, patternExp = attr.ngPattern || attr.pattern; //The postLink fn guarantees we overwrite the built-in pattern validator ctrl.$validators.pattern = function(value) { return ctrl.$isEmpty(value) || angular.isUndefined(regexp) || regexp.test(value); }; } }; } }; }); 

Problem in ui-mask GitHub - Link .

0
source

Source: https://habr.com/ru/post/1212162/


All Articles