Nikki J
Nikki J

Reputation: 1

Optional UI-Masking for zipcode to accept either 5 or 9 digits

Using UI_mask, I want a zipcode to be accepted as either (xxxxx-xxxx or xxxxx).

In order to do this, I have used

< input type="text" name="zipcode" ui-mask="99999?-9999" ui-mask-placeholder ng-model="zipCode">

But this accepts 8 or 9 digits and has a placeholder of (_____-____).

Is there any way to accept either 5 or 9 digits (using ui-mask) ?

Upvotes: 0

Views: 2734

Answers (1)

Bernardo Baumblatt
Bernardo Baumblatt

Reputation: 404

There are no way to accept only 5 OR 9 digits only with angular-ui-mask, but this could be done with help of angular-ui-validate.

The angular-ui-mask for the mask and validation between 1 to 5 digits.

The angular-ui-validate for validation between 6 to 9 digits.

Please take a look on the working snipped below.

var app = angular.module('myApp', ['ui.mask', 'ui.validate']);
app.controller('MainController', ['$scope', function ($scope) {
    $scope.formData = {'zip': ''};
    $scope.validateZip = function(zip) {
        // no zip code is valid. left this for 'required'.
        if(!zip) return true; 
        // true if 5 or 9 digits
        return zip.match(/^(\d{5}|\d{9})$/);
    }
}]);

angular.bootstrap(document.getElementById('myApp'), ['myApp']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-mask/1.8.7/mask.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-validate/1.2.2/validate.min.js"></script>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css">

<div id="myApp" class="container">
  <form name="myForm">
    <div class="form-group" ng-controller="MainController" ng-class="{'has-error': myForm.zipcode.$error.mask || myForm.zipcode.$error.validator}">
      <label for="zipcode">Zip code:</label>
      <input type="text" ng-model="formData.zip" ui-mask="99999?-?9?9?9?9" ui-validate="'validateZip($value)'" class="form-control" id="zipcode" name="zipcode">
      <span class="help-block" ng-if="myForm.zipcode.$error.mask" >Invalidated by ui-mask</span>
      <span class="help-block" ng-if="myForm.zipcode.$error.validator">Invalidated by ui-validator</span>
    </div>
  </form>
</div>

Upvotes: 2

Related Questions