1

I am trying to use the UK Post code regular expression given in this answer https://stackoverflow.com/a/164994/4950 in a RegularExpression Data Annotation for Model validation in ASP.NET MVC.

Here's the RegEx:

(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})

This works fine serverside and when tested in Regex hero (http://regexhero.net/tester/) but on the client side the regular expression does not seem to work.

I have looked at the code that the Jquery.validate.unobtrusive plugin is using:

$jQval.addMethod("regex", function (value, element, params) {
    var match;
    if (this.optional(element)) {
        return true;
    }

    match = new RegExp(params).exec(value);
    return (match && (match.index === 0) && (match[0].length === value.length));
});

and sort of replicated the same situation here: http://jsfiddle.net/cEGsj/ (I added the gi params later).

Can anyone tell me why this Regular expression is failing in JS? I thought initially it was to do with casing but adding the ignore case option does not seem to change anything.

Also doesn't seem to work here: http://regexpal.com/ So there must be some syntax issue..

Update: I have managed to get something satisfactorily working by removing the nested character sets. See working example here: http://jsfiddle.net/Asyqh/1/

Community
  • 1
  • 1
Rob Stevenson-Leggett
  • 35,279
  • 21
  • 87
  • 141

1 Answers1

0

I have managed to get something satisfactorily working by removing the nested character sets which Javascript does not seem to like. See working example here: http://jsfiddle.net/Asyqh/1/

var regex = "(GIR 0AA)|((([A-Z][0-9][0-9]?)|(([A-Z][A-Z][0-9][0-9]?)|(([A-Z][0-9][A-HJKSTUW])|([A-Z][A-Z][0-9][ABEHMNPRVWXY])))) [0-9][A-Z]{2})";
Rob Stevenson-Leggett
  • 35,279
  • 21
  • 87
  • 141