1

I need a javascript reg ex that forces the user to enter a space in their UK post code.

Can somebody please help? Those I have found seem to allow for optional spaces which is not what I'm after.

lunchboxbill
  • 191
  • 3
  • 15
  • 1
    At the very least you could tell us what a valid UK post code is – Explosion Pills Feb 19 '13 at 23:19
  • 1
    Related: http://stackoverflow.com/q/164979/1615483 – Paul S. Feb 19 '13 at 23:28
  • 1
    No offence, but if you are forcing users to do this then you're going to annoy your users. Allow them to enter it with or without spacing, and then reformat it yourself afterwards. –  Feb 19 '13 at 23:33
  • @jgm what really annoys me is when websites don't allow `+` signs in email addresses. I like to follow where addresses I give out end up. – Paul S. Feb 19 '13 at 23:42
  • it probably will annoy the users (especially for ones who have already entered it and will have to change on payment page) but it's something I can't get around. – lunchboxbill Feb 20 '13 at 21:28

1 Answers1

1

Something like this? Believe it catches all UK postcodes, at least it caught all the ones I can think of off the top of my head

/^(\w{1,2}\d{1,2}\w?\s\d\w{1,2})$/
Ross McLellan
  • 1,872
  • 1
  • 15
  • 19
  • Ross, does this force a space to entered? – lunchboxbill Feb 20 '13 at 21:29
  • Yes. There's no `?` after the `\s` (space) which means it must be there for the expression to match. So the whole expression reads: 1 or 2 letters (\w), followed by 1 or 2 numbers (\d) followed by 0 or 1 letters. A space. 1 number and then 1 or 2 letters. – Ross McLellan Feb 21 '13 at 09:42