JSFiddle - React, Tailwind, and code Playground
HTML
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<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>
CSS
.field-validation-error{
color:red;
}
JavaScript
//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;
};
}]);