I am trying to write Regex for New Zealand address validation. This is the valid character set which I want to capture, must start with a number and case insensitive which includes letters A to Z, numbers (0-9) and hyphen "-" and forward slash "/" as well as Maori accented characters for Maori vowels ā, ē, ī, ō, ū and works in JavaScript to display an invalid error message, just not with the HTML5 form validation.
...
// JavaScript regex
var regex = /^\d[\/a-zĀ-ū0-9\s\,\'\-]*$/i;
...
Because I am attempting to do this in BigCommerce and don't have access to edit the input I am applying the "pattern" HTML input attribute with JavaScript. I really did think it was as simple as stripping "/^" from the start of the regex and "$/" from the end of the regex when applying to the HTML pattern attribute:
...
/** @start JavaScript code for HTML5 form validation **/
let fulladdress = document.getElementById('addressLine1Input');
fulladdress.setAttribute("pattern", "\d[\/a-zĀ-ū0-9\s\,\'\-]*");
fulladdress.addEventListener('input', () => {
fulladdress.setCustomValidity('');
fulladdress.checkValidity();
});
fulladdress.addEventListener('invalid', () => {
fulladdress.setCustomValidity('No PO Box or Private Bag address must start with a number, e.g. 1/311 Canaveral Drive');
});
/** @end JavaScript code for HTML5 form validation **/
...
HTML snippet:
...
<input id="addressLine1Input" name="shippingAddress.address1" placeholder="Enter your address" onFocus="geolocate()" type="text" class="form-control" onblur="validateAddress()" required>
...
I created a JSFiddle, the lines of interest are 13 - 26 on the JavaScript area JSFiddle example
This is an invalid address string:
Flat 1 311 Point Chevalier Road, Point Chevalier, Auckland 1022, New Zealand
This is a valid address string:
1/311 Point Chevalier Road, Point Chevalier, Auckland 1022, New Zealand
The form validation pops up once you enter an address and click the Submit button
Thank you really appreciate the input from the community.
This code works perfectly for all the validation examples I want, if there is a way to use it with HTML5 tool tips and form validation that would serve as a very viable workaround:
var regex = /^.*(po\s*box|private\s*bag).*$|^\d[\/a-zĀ-ū0-9\s\,\'\-]*$/i;
...
function validateAddress() {
var str = getValue();
var match = str.match(regex);
var tooltip = document.getElementById("notification");
var msg = document.getElementById("msg");
if (match && !match[1]) {
// valid address
msg.innerHTML = "<p>Address looks to be valid</p>";
tooltip.style.display = 'none';
} else {
// invalid address
msg.innerHTML = "<p>Invalid address (No PO Box or Private Bag address must start with a number, e.g. 1/311 Canaveral Drive)</p>";
tooltip.style.display = 'block';
}
}
...