From 8551a15215b0a780a8b0d401907276ac39c53612 Mon Sep 17 00:00:00 2001 From: TomCrawshaw Date: Thu, 15 Apr 2021 15:36:40 +0100 Subject: [PATCH] Add postcode validation Most postcode lookup providers deduct a credit for each search, so that partially entered postcodes were costing a credit. This mod adds a postcode validation routine to check that a full postcode has been entered, so that only one call is made. --- js/civipostcode_component.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/js/civipostcode_component.js b/js/civipostcode_component.js index 2bd6fbe..175d96e 100644 --- a/js/civipostcode_component.js +++ b/js/civipostcode_component.js @@ -4,6 +4,19 @@ jQuery(document).ready(function ($) { var sourceUrl = Drupal.settings.baseUrl + "/civicrm/" + civiPostCodeLookupProvider + "/ajax/search?json=1"; $.each(civiPostCodeFields, function (key, value) { if ($('[id*="'+value+'"]').length) { // Check postcode element exists on page first + $('[id*="' + value + '"]').on('keyup', function (event) { + // Simple regex for postcode structure checking, without complexity of checking for allowable letters + // See https://stackoverflow.com/questions/164979/regex-for-matching-uk-postcodes for more! + var regex = new RegExp('^([A-Za-z]{1,2}[0-9]{1,2}[A-Za-z]?[ ]?)([0-9]{1}[A-Za-z].*)'); + // Check entry up to penultimate character, to allow autocomplete to work after final char + if(regex.test($('[id*="' + value + '"]').val())) + { + $('[id*="' + value + '"]').autocomplete( "option", "disabled", false ); + }else + { + $('[id*="' + value + '"]').autocomplete( "option", "disabled", true ); + } + }); $('[id*="' + value + '"]').autocomplete({ source: sourceUrl, minLength: 3,