DHeadshot
DHeadshot

Reputation: 43

Javascript Regular Expression Error Testing a Postcode

I'm trying to use the postcode regular expression specified here: UK Postcode Regex (Comprehensive) with javascript, but it doesn't seem to work. I'm using:

var postcode = "^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$";
var aPCode = frm.PCode.value;
if (!(postcode.test(aPCode)))
{
  AnError += "Invalid Postcode.\n";
}

The error I'm getting is with the if (!(postcode.test(aPCode))) line. IE7 (the browser where I have JavaScript errors enabled) reports back with the error "Object doesn't support this property or method.". This implies that I cannot use the .test method on a string, but that's where it's supposed to be used, isn't it? I can't seem to find the fault with my code.

Upvotes: 0

Views: 337

Answers (1)

Sterling Archer
Sterling Archer

Reputation: 22435

postcode is a string, not a regular expression. Wrap it in forward slashes and remove the wrapping quotes to make it a regular expression:

var postcode = /^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$/;

see the docs

Or run the string version of the regular expression into the RegExp object to convert it:

var postcode = "^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$";
var postcode = new RegExp(postcode);

Upvotes: 1

Related Questions