0

I'm having issues getting ng-pattern working for any postcode regex in my code. I've tried a couple simple regexs and they are fine.

The regexs i've been using are from UK Postcode Regex (Comprehensive)

eg: $scope.UKGovPostcodeRegex = "(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})";

Error: Syntax Error: Token '0' is unexpected, expecting [)] at column 6 of the expression [(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})] starting at [0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})].

Has anyone successfully implemented postcode validation in angularjs v1.1.5?

Community
  • 1
  • 1
nWardy
  • 117
  • 9

1 Answers1

1

I don't know why that doesn't work, but this seems to:

$scope.UKGovPostcodeRegex = /^ ... $/;

(Replace ... with your regex.)

Then use it like this: ng-pattern='UKGovPostcodeRegex'

You need the ^ and $ or else it will match any string that has a postcode as a substring.

TimK
  • 4,635
  • 2
  • 27
  • 27
  • Thanks very much for your answer! I used this in combination with a simplified regex to get the solution I needed. $scope.UKGovPostcodeRegex = /^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$/; ng-pattern='UKGovPostcodeRegex' – nWardy Oct 16 '13 at 14:27