Skip to content

Instantly share code, notes, and snippets.

@BrettBailey
Created June 1, 2015 23:30
Show Gist options
  • Save BrettBailey/4e6b5f3cf1e0ce3eff56 to your computer and use it in GitHub Desktop.
Save BrettBailey/4e6b5f3cf1e0ce3eff56 to your computer and use it in GitHub Desktop.
UK Postcode Validator using angular js and ng-pattern. Full Explanation at http://www.clearcoders.co.uk/
<div class="form-group">
<div class="col-xs-7">
<label for="postcode">Postcode</label>
<input type="text" name="postcode" placeholder="Postcode" ng-pattern="/^[a-z]{1,2}[0-9][a-z0-9]?\s?[0-9][a-z]{2}$/i" required ng-minlength="5" ng-maxlength="8" ng-model="complaint.postcode" ng-change="formatPostcode()" class="form-control" />
<div class="col-xs-12" ng-messages="reclaim.postcode.$error" ng-if="reclaim.$submitted || reclaim.postcode.$dirty">
<div class="text-warning" ng-message="minlength">Postcode is too short.</div>
<div class="text-warning" ng-message="pattern">Postcode is not in the correct format.</div>
<div class="text-warning" ng-message="maxlength">Postcode is too long.</div>
</div>
</div>
</div>
@moafzalmulla
Copy link

Hey @BrettBailey, Great script

I am new to using angular for this postcode purpose.

I have lncluded the script in my page, and also added <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script> in the footer along with : <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script type="text/javascript">
$scope.formatPostcode = function() {
var postcode = $scope.complaint.postcode.toUpperCase(),
index = postcode.length - 3;

  if (postcode.charAt(index - 1) == " ") return;

  return $scope.complaint.postcode = postcode.substr(0, index) + ' ' + postcode.substr(index);

}
</script>

However it does not work and still show all 3 errors on pageload ?

Any idea what I could be doing wrong ?

Best,
Mo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment