Postcode Validation with Regex

I am fumbling/hacking my way through my first Javscript code but have now hit some stumbling blocks.

I’ve recycled some functions I found online which use regex to validate and format UK postcodes. I really can’t get my head around how they work though :slight_smile:

The code should work as follows

  1. User types in postcode (this could be a full uk postcode i.e. NW11 1AG or a short version NW11 or full postcode not formatted NW111AG.

  2. There is a list of allowed postcodes stored with a variable or array. The list will only contain the first part of the postcode i.e. NW11 or N1 etc.

  3. Code then checks whether users postcode is within list

  4. Dialog box tells user if postcode is allowed or not.

I think the code is now structured in the correct way but am struggling with a couple of things.

(a) How do I change this line to use the ‘pc’ variable not the hard coded list which is in place.

if ([“foo”, “bar”, “BS3 1PZ”].exists(shortenPostcode(x))) {

Something like below (which doesn’t work - think something to do with ")?

if ([pc].exists(shortenPostcode(x))) {

(b) How do I tweak function shortenPostcode to just return the first part of the postcode? It works at the moment if you type TW11PA but not if you type TW1 1PA

(c) Any other suggestions on how I could improve structure of my code and/or speed.

Full code


<html>
<head>

<script type="text/javascript">

function validateForm()
{
/*set up form variable */
var x=document.forms["myForm"]["postcode"].value;
var pc="foo, bar, BS3 1PZ"

/*check if user has entered short post e.g. NW1 and is in pc list */
if (["foo", "bar", "BS3 1PZ"].exists(shortenPostcode(x))) {
	alert("Postcode in list - no further checking required")
	alert ("Formatted postcode" + formatPostcode(x))
	alert ("Shortened postcode" + shortenPostcode(x))
	
}
	else {

/*Check if user has entered a valid postcode. */
	if (isValidPostcode(x)) {
	/*If valid check if shortened version is within list  */
		if (["foo", "bar", "BS3 1PZ"].exists(shortenPostcode(x))) {
			alert ("In List")
			alert ("Formatted postcode" + formatPostcode(x))
			alert ("Shortened postcode" + shortenPostcode(x))
			}
		else {
			alert ("Not In List")
			alert ("Formatted postcode" + formatPostcode(x))
			alert ("Shortened postcode" + shortenPostcode(x))
			}  
	}
else
	alert("This is not a valid postcode");
	
		}	
}

/* tests to see if string is in correct UK style postcode: AL1 1AB, BM1 5YZ etc. */
function isValidPostcode(p) {
	var postcodeRegEx = /[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} ?[0-9][A-Z]{2}/i;
	return postcodeRegEx.test(p);
}

/*	formats a VALID postcode nicely: AB120XY -> AB1 0XY */
function formatPostcode(p) {
        if (isValidPostcode(p)) {
                var postcodeRegEx = /(^[A-Z]{1,2}[0-9]{1,2})([0-9][A-Z]{2}$)/i;
                return p.replace(postcodeRegEx,"$1 $2");
                return 
        } else {
                return p;
        }
}

/*	returns the first part of a postcode */
function shortenPostcode(p) {
        if (isValidPostcode(p)) {
                var postcodeRegEx = /(^[A-Z]{1,2}[0-9]{1,2})([0-9][A-Z]{2}$)/i;
                return p.replace(postcodeRegEx,"$1");
                return 
        } else {
                return p;
        }
}

/* function to search postcode array */
Array.prototype.exists = function(search){
  for (var i=0; i<this.length; i++)
    if (this[i] == search) return true;
		
  return false;
} 


</script>
</head>

<body>
<form name="myForm" onsubmit="validateForm();" method="post">
Email: <input type="text" name="postcode">
<input type="submit" value="Submit">
</form>
</body>

</html>