问题描述:

I'm trying to validate UK postcodes using javascript and as far as I can tell from reading on threads on stack, the following should work fine. However no matter what valid UK postcode I've tried so far, the if statement fails. I'm a bit of a newb to javascript,

var postcode = $("#postcode").val().toUpperCase();

var regex = new RegExp("^((GIR &0AA)|((([A-PR-UWYZ][A-HK-Y]?[0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]))) &[0-9][ABD-HJLNP-UW-Z]{2}))$");

if(regex.test(postcode)){

alert('yes');

} else {

alert('no');

}

网友答案:

As mentioned in comments, your problem seems to be the ampersands &. Somewhat simplified and corrected I believe your regex should be:

^(GIR 0AA|(?:[A-PR-UWYZ][A-HK-Y]?[0-9][0-9]?|[A-PR-UWYZ][0-9][A-HJKSTUW]|[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]) [0-9][ABD-HJLNP-UW-Z]{2})$

Capturing the whole value, from begining of line to end, it matches

Girobank's PC

or

one of the other combinations (separated by | inside a non-capturing group (?:...)) followed by the terminating space, digit, letter, letter.

Hope this helps.

Regards

相关阅读:
Top