Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngPattern binding not working

I want to validate an input using ngPattern based off of the selection of a select. It works after the first selection, but any subsequent selection does't bind correctly.

Here's a jsFiddle for reference: http://jsfiddle.net/PLRf5/17/

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
    <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" />
    <style>
        .field-validation-error {
            color: red;
        }
    </style>
</head>
<body>
   <div class="container form-group" ng-app="mod1" ng-controller="ctrl1">
        <p>
            ng-pattern binding is not updating:
            Enter in 'asdf' then click Cuba. ngPattern should update and you should not see "Bad Format".
        </p>

        <div ng-form="genericAddressEntry">
            <div class="form-group" data-ng-class="{ 'has-error': genericAddressEntry.country.$invalid }">
                <label for="country">Country</label>
                <select name="country" class="form-control"
                    data-ng-model="selectedCountry"
                    data-ng-options="country as country.name for country in countries"
                    data-ng-required="true"
                    >
                </select>
            </div>

            <div class="clearFix" ng-bind="selectedCountry | countryToPostalCodeRegex"></div>

            <div class="form-group " data-ng-class="{ 'has-error': genericAddressEntry.postalCode.$invalid }">
                <label for="postalCode">Zip Code</label>

                <input name="postalCode" type="text" class="form-control" data-ng-model="editAddress.postalCode" data-ng-required="selectedCountry.requiresPostal"
                    ng-pattern="selectedCountry | countryToPostalCodeRegex" maxlength="12" />
                <span class="field-validation-error" data-ng-show="genericAddressEntry.postalCode.$error.pattern">Bad Format</span>
                <span class="field-validation-error" data-ng-show="genericAddressEntry.postalCode.$error.required">Required</span>
            </div>

        </div>
    </div>

    <script>


        //module:
        angular.module('mod1', [])
          .controller('ctrl1', ['$scope', function ($scope) {
           //   $scope.editAddress = { postalCode: "12345" };
              $scope.countries = [
              { name: 'United States', requiresPostal: true, postalRegEx: '^[0-9]{5}([-]?[0-9]{4})?$' },
              //{ name: 'Canada', requiresPostal: true, postalRegEx: '^[a-yA-Y]\d[a-zA-Z]( )?\d[a-zA-Z]\d$' },
              { name: 'Cuba', requiresPostal: false, postalRegEx: undefined }];
              $scope.selectedCountry = $scope.countries[0];
          }])
          .filter('countryToPostalCodeRegex', [function () {
              var allowAllRegex = new RegExp("^.*");
              var escapeRegex = function (str) {
                  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
              }

              return function (country) {

                  if (!country) {
                      return allowAllRegex;
                  }
                  if (!country.requiresPostal) {
                      return allowAllRegex;
                  }

                  if (!country.postalRegExObj) {
                      country.postalRegExObj = new RegExp(escapeRegex(country.postalRegEx), "i");
                  }
                  return country.postalRegExObj;
              };
          }]);
    </script>

</body>
</html>
like image 207
Cirem Avatar asked Dec 30 '13 21:12

Cirem


3 Answers

Currently Angular doesn't monitor attributes for changes it only monitors bound values. There's a couple Angular issues that discuss this further NgMinlength And NgMaxlength - Set length value dynamically not working and input does not watch ngPattern value for changes. Two key comments from caitp are:

The general pattern of Angular isn't to respond to actual changes to an attribute value, but rather to respond to changes to a bound value.

and

The thing with this is that currently the pattern doesn't come from a parsed expression / scope variable, it's just a string literal turned into a regexp, so watching for changes to that means essentially watching the DOM attribute value for change. I think I mentioned that on a different issue regarding this a few weeks ago. Watching changes to the actual DOM attribute is fairly different from what angular is typically doing.

Taking a cue from those issues, and looking at how Angular implements ngPattern one way to handle this is to add a directive that watches the Angular eval() of the ngPattern attribute for changes. If it sees a change then it can evaluate the ngPattern regex and setValidity.

This gives us dynamic monitoring of the attributes value. Here's the directive:

.directive('updatePattern', function() {
    return {
       require: "^ngModel",
       link: function(scope,element,attrs,ctrl) {
               scope.$watch(function() {
                  // Evaluate the ngPattern attribute against the current scope
                  return  scope.$eval(attrs.ngPattern); 
               },
               function(newval, oldval) {
                  //Get the value from `ngModel`
                  value = ctrl.$viewValue;

                  // And set validity on the model to true if the element 
                  // is empty  or passes the regex test
                  if (ctrl.$isEmpty(value) || newval.test(value))   {
                     ctrl.$setValidity('pattern', true);
                     return value;
                  } else {
                     ctrl.$setValidity('pattern', false);
                     return undefined;
                 }
              });                                            
            }
        }
    });

And we add our new update-pattern directive to the html:

<input name="postalCode" type="text" class="form-control" data-ng-model="editAddress.postalCode" data-ng-required="selectedCountry.requiresPostal"
                    ng-pattern="selectedCountry | countryToPostalCodeRegex" maxlength="12" update-pattern />

working fiddle

like image 159
KayakDave Avatar answered Nov 20 '22 18:11

KayakDave


I have a simple way to solve this problem.

Using pattern instead of ng-pattern.

If you had checkout angular source code, you will found out that pattern and ng-pattern is same directive.

There are two different between pattern and ng-pattern:
1. angular will observe pattern changes. (That what's we need!)
2. angular will prepend ^ and append '$' to pattern

$scope.regex = '\\d\\d'; //angular will convert this to ^\d\d$
$scope.UPPERCASE = '\\D\\D';

HTML:

<input name="test" pattern="regex">
<!-- I can use filter to change my wrong UPPERCASE regex to correct.-->
<input name="test2" pattern="UPPERCASE | lowercase">
like image 4
Eric Chen Avatar answered Nov 20 '22 16:11

Eric Chen


Solution from @KayadDave is the perfect one, but you can use a workaround: call $setViewValue manually to force ng-pattern evaluation :

<!-- Add ng-change function -->
<select name="country" class="form-control"
        data-ng-model="selectedCountry"
        data-ng-options="country as country.name for country in countries"
        data-ng-required="true"
        data-ng-change="updatePattern()"
>
</select>

In you controller:

$scope.updatePattern = function() {
    var postalCode = $scope.genericAddressEntry.postalCode;
    postalCode.$setViewValue(postalCode.$viewValue);
};
like image 1
Mickael Avatar answered Nov 20 '22 16:11

Mickael