The following script will take the input from the form and validate a post code in UK Format eg. Lettter Letter Number Number Letter Letter
<!DOCTYPE html>
<html>
<head>
<title>UK Postcode Validation</title>
<script type="text/javascript">
function isValidUKPostcode(postcode) {
var postcodePattern = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]?))))\s?[0-9][A-Za-z]{2})$/;
return postcodePattern.test(postcode);
}
function validateForm() {
var postcodeInput = document.getElementById("postcode").value;
var errorDiv = document.getElementById("error-message");
if (!isValidUKPostcode(postcodeInput)) {
errorDiv.innerText = "Please enter a valid UK postcode.";
return false;
}
errorDiv.innerText = ""; // Clear any previous error message
return true;
}
</script>
<style>
.error {
color: red;
margin-top: 5px;
}
</style>
</head>
<body>
<form action="process_form.php" method="POST" onsubmit="return validateForm()">
<label for="postcode">Enter UK Postcode:</label>
<input type="text" id="postcode" name="postcode" required>
<div id="error-message" class="error"></div>
<input type="submit" value="Submit">
</form>
</body>
</html>
Disclaimer: The code on this website is provided "as is" and comes with no warranty. The author of this website does not accept any responsibility for issues arising from the use of code on this website. Before making any significant changes, ensure you take a backup of all files and do not work directly on a live/production website without thoughly testing your changes first.