DannyDanDan
DannyDanDan

Reputation: 36

Validation RegExp Issue

I know there are lots of questions related to validation but, after looking at so many on SO I can't seem to fix this what so ever.

I'm trying to match a postcode to a regular expression I have found on SO. The fiddle says the postcode is invalid, yet when I test the regular expression on rubular.com it works fine

Rubular Image

JS Fiddle https://jsfiddle.net/aeqawadv/1/

<div id="test"></div>

<script type="text/javascript">
    var string = "SK13 6NT";
    var ukPostcode = new RegExp(/^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$i/);
    if (ukPostcode.test(string)) {
        document.getElementById("test").innerHTML="Valid";
    } else {
        document.getElementById("test").innerHTML="Invalid";
    }
</script>

Any ideas? I've also tried match() as oppose to test()

EDIT

Just realised I was using rubular instead of scriptular but, result is still the same

Upvotes: 0

Views: 36

Answers (2)

hwnd
hwnd

Reputation: 70732

Remove the i after your end of string $ anchor, and why not use a regular expression literal?

var ukPostcode = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/

If i was supposed to be used as the case-insensitive modifier, place it after your delimiter.

var ukPostcode = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i

Upvotes: 1

Peter Bowers
Peter Bowers

Reputation: 3093

You have an "i" after your dollar-sign at the end of it.

var ukPostcode = new RegExp(/^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$i/);

should be

var ukPostcode = new RegExp(/^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/);

or (if you were aiming for case-insensitivity)

var ukPostcode = new RegExp(/^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i);

Upvotes: 1

Related Questions