Validating Postcodes with a Regular Expression

I have just had an issue where form validation will pass for the following postcode:

ec1r 5ar <script>alert("hi")</script>

The only reason being the fact that there is a valid post code at the beginning. I was using a very slightly adapted regular expression found on the Wikipedia Postcodes article which was:

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

So getting my regex hat on. I had the issue that it cannot allow anything after the validated postcode, but also I expect that it would similarly allow junk before the valid postcode. The whole thing is wrapped in matching brackets so all I needed to do was add the begins with (^) and ends with ($) simbols to fix the test with the following regex:

var rege = /^(GIR 0AA|[A-PR-UWYZ]([0-9][0-9A-HJKPS-UW]?|[A-HK-Y][0-9][0-9ABEHMNPRV-Y]?)[ ]?[0-9][ABD-HJLNP-UW-Z]{2})$/i;

console.log(rege.test('ec1r 5ar <script>alert("hi")</script>'))

And this test fails, whoop!

Work with me

Dave is a cohesive team member, widely popular with his colleagues and always inspiring quality, exploration and innovation. One of the true ‘greats’ we’ve had the pleasure to work with

I believe in community, in inspiration and creativity. I believe it's an inspired team and a laser focus on the user's experiece that will produce the best results. I want to help frontend teams live inspired, be productive and scale better.