UK Postcode Frontend Validation

Looking to ensure postcodes are submitted in the correct format? Look no further!

Korey Abbott avatar
Written by Korey Abbott
Updated over a week ago

PLEASE NOTE: This guide requires some technical ability, a familiarity with HTML and Javascript. It is for front end templates and does not relate to back end validation.
​
The below assumes you have a Databowl field with F_11_POSTCODE and a submit button with a class of 'continue'. This code would be wrapped within a form and fieldset tag.

HTML
​

<div class="field" id="postcode">
<field-yield data-field="F_11_POSTCODE"></field-yield> <div class="error-message"></div> </div>
<button type="submit" data-db-localized-content="FORM_SUBMIT"></button>


JavaScript

$(function(){
$("form#form-1 input[name='F_11_POSTCODE']").change(function () {
var p = $(this).val();
var wrapper = $("#postcode");
$("input[name='F_11_POSTCODE']").html(p)
$("input[name='F_11_POSTCODE']").html(isValidPostcode(p))
if (isValidPostcode(p)) {
// there is a mismatch, hence show the error message
wrapper.removeClass('has-error');
$('.continue').prop("disabled", false);
$('.continue').css("opacity", "1");
wrapper.find(".error-message").html("");
console.log("passed check")
}
else {
// else, do not display message
wrapper.removeClass('field-valid');
$('.continue').prop("disabled", true);
$('.continue').css("opacity", "0.75");
wrapper.addClass('has-error');
wrapper.find(".error-message").html("Please enter a valid postcode");
console.log("failed check")
}
});
});
//postcode v
function isValidPostcode(p) {
var postcodeRegEx = /^([A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}|GIR ?0A{2})$/gim;
return postcodeRegEx.test(p);
}


πŸš€ Need More assistance?

If you're stuck or if this isn't something you or your team is comfortable with, then please open a new chat/ticket (chat icon in the bottom right of the screen) or email support@databowl.com.

We're here to assist with any questions you have, and if required we can quote on actioning work like this for as part of our Marketing Services.

Did this answer your question?