0

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

0

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Or maybe it was supposed to be a case insensitive flag. Then the i should appear after the second /.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.