function validPostcode(frmElement){

var pcode = frmElement.value;
var pcType = new Array();

pcType[0] = /^[A-Z]{1}\d{1}\s{1}\d{1}[A-Z]{2}/;
pcType[1] = /^[A-Z]{2}\d{1}\s{1}\d{1}[A-Z]{2}/;
pcType[2] = /^[A-Z]{1}\d{2}\s{1}\d{1}[A-Z]{2}/;
pcType[3] = /^[A-Z]{2}\d{2}\s{1}\d{1}[A-Z]{2}/;
pcType[4] = /^[A-Z]{2}\d{1}[A-Z]{1}\s{1}\d{1}[A-Z]{2}/;
pcType[5] = /^[A-Z]{1}\d{1}[A-Z]{1}\s{1}\d{1}[A-Z]{2}/;

var sAlertEmpty = "Please enter a valid UK postcode.";
var sAlertLength = "Sorry, but the postcode you entered was too long or too short. Please enter a valid UK postcode.";
var sAlertInvalid = "Sorry, but the postcode you entered was not valid. Please enter a valid UK postcode.";
	
	if (pcode==null||pcode==""){alert(sAlertEmpty);return false;}
	
	pcode = formatPostcode(pcode);
	
	if (pcode.length<6||pcode.length>8){alert(sAlertLength);return false;}
	
	for(i=0; i<pcType.length; i++) {
		if (pcode.match(pcType[i])) {
			frmElement.value = pcode; 
			return true;
		}
	}
	
	alert(sAlertInvalid);
	return false;
}

function formatPostcode(xPC){

	xPC = xPC.toUpperCase();

	// replace all spaces
	xPC = xPC.replace(/\s+/g, "");

	// now put the space back in the right place
	xLen = xPC.length;
	xLastStart = xLen - 3;
	xPart1 = xPC.substr(0, xLastStart);
	xPart2 = xPC.substr(xLastStart, 3);
	xPC = xPart1 + " " + xPart2;
	return xPC;
}

function validate(frm){
	if (!validPostcode(frm.postcode)){return false;}
	else {return true;}
}
