One of the functions in the program is a user entering their postcode. So far I have:
if ( postcode != //SOMETHING// )
{
JOptionPane.showMessageDialog(this, "Not UK Postcode", "Postcode must be a valid UK postcode", jOptionPane.ERROR_MESSAGE);
}
What would I put in the if statement in order for it to check if the entered postcode is a valid UK postcode?
There are some special codes, such as GIR 0AA and SAN TA1 which haven't been mentioned in the formats previously given.
The letter J is never found as one of the first two letters. The letters Q, V and X are never found in the first position of the postal code. The letters I and Z are not found in the second position (except for the single postal code GIR 0AA ). Where the third position is a letter, the letters I, L, O, Q and Z are not found. Only the letters A, B, E, H, M, N, P, R, V, W, X and Y can appear in the fourth position. In the part of the postal code after the space, the letters C, I, K, M, O and V are never found.
A regex for validating current UK postal codes is:
\A((GIR 0AA)|(SAN TA1)|[A-I|K-P|R-U|W|Y-Z]0-9[0-9][A-B|D-H|J|L|N|P-U|W-Z][A-B|D-H|J|L|N|P-U|W-Z]|[A-I|K-P|R-U|W|Y-Z][0-9]0-9[0-9][A-B|D-H|J|L|N|P-U|W-Z][A-B|D-H|J|L|N|P-U|W-Z]|[A-I|K-P|R-U|W|Y-Z][0-9]A-H|J-K|M-N|P|R-Y[0-9][A-B|D-H|J|L|N|P-U|W-Z][A-B|D-H|J|L|N|P-U|W-Z]|[A-I|K-P|R-U|W|Y-Z][A-H|K-P|R-U|W|Y]0-9[0-9][A-B|D-H|J|L|N|P-U|W-Z][A-B|D-H|J|L|N|P-U|W-Z]|[A-I|K-P|R-U|W|Y-Z][A-H|K-P|R-U|W|Y][0-9]0-9[0-9][A-B|D-H|J|L|N|P-U|W-Z][A-B|D-H|J|L|N|P-U|W-Z]|[A-I|K-P|R-U|W|Y-Z][A-H|K-P|R-U|W|Y][0-9]A-H|J-K|M-N|P|R-Y[0-9][A-B|D-H|J|L|N|P-U|W-Z][A-B|D-H|J|L|N|P-U|W-Z])\Z
You can find more information on UK postal codes at http://www.grcdi.nl/gsb/united%20kingdom.html