﻿
function validateUKPostcode(__postcode)
{ 
	//check postcode format is valid

 	var len=__postcode.length; __postcode=__postcode.toUpperCase().trim();
	
	//code length rule
	if (len < 6 || len > 8) return " is not a valid postcode - wrong length";
		
	//leftmost character must be alpha character rule
	if (!(isNaN(__postcode.charAt(0)))) return " is not a valid postcode - cannot start with a number";
	
	//first character of inward code must be numeric rule
	if(isNaN(__postcode.charAt(len-3))) return " is not a valid postcode - alpha character in wrong position";
	
	//second character of inward code must be alpha rule
	if (!(isNaN(__postcode.charAt(len-2)))) return " is not a valid postcode - number in wrong position";
		
	//third character of inward code must be alpha rule
	if (!(isNaN(__postcode.charAt(len-1)))) return " is not a valid postcode - number in wrong position";
		
	//space in position length-3 rule
	if (!(__postcode.charAt(len-4) == " "))return " is not a valid postcode - no space or space in wrong position";
	
	//only one space rule
	if (__postcode.indexOf(" ") != __postcode.lastIndexOf(" "))return " is not a valid postcode - only one space allowed";
	
	return "";
}