I have a web app which works fine but I would like to validate a UK postcode as the input postcode field is entered (if possible). A code snippet of the HTML input field is included with the regex suggested, but I have no idea how to validate the regex - either from a function within the HTML file or from the originating code.
<div class="cell-6">
<div class="form-group">
<label>Post Code</label>
<input name="postcode" type="text" placeholder="Post Code" class="metro-input" data-validate="pattern='([a-zA-Z]{1,2}\d{1,2}[a-zA-Z]? ?\d[a-zA-Z]{2}|GIR ?0AA)'">
</div>
</div>
The first part of the Code.gs file is here
function doGet() {
const htmlService = HtmlService.createTemplateFromFile("index")
// var pictures = getPictures();
// htmlOutput.pictures = pictures;
htmlService.timestamp = getTimestamp()
htmlService.courses = getCourses_()
htmlService.ethnics = getEthnics_()
htmlService.ages = getAges_()
htmlService.myunions = getMyUnions_()
htmlService.pictures = getPictures()
htmlService.img = getImage()
const html = htmlService.evaluate().addMetaTag("viewport","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no")
return html
}
function acceptData(formData){
console.log(formData)
console.log([formData.firstName])
const ss = SpreadsheetApp.openById("1D4JuWXxTtLqmM9o5pa2pv18NW9qZOIXJXavv777sgpA")
const ws = ss.getSheetByName("Registrations")
ws.appendRow([
formData.timestamp,
formData.firstName,
formData.lastName,
formData.mobile,
formData.postcode,
formData.course,
formData.accommodation,
formData.emergencyname,
formData.emergencynumber,
formData.healthadjustments,
formData.dietary,
formData.ethnic,
formData.gender,
formData.disabled,
formData.lgbt,
formData.myunion,
formData.hearaboutus,
formData.fee,
formData.dataprotection
])
}
<form method="post" onsubmit="return validatePostcode()">
<input name="postcode" id="postcode" type="text" placeholder="Post Code" class="metro-input" required>
<button type="submit">Submit</button>
</form>
<script>
function validatePostcode() {
const postcode = document.getElementById("postcode").value.trim();
const regex = /^([A-Z]{1,2}\d{1,2}[A-Z]? ?\d[A-Z]{2}|GIR ?0AA)$/i;
if (!regex.test(postcode)) {
alert("Invalid UK postcode format.");
return false;
}
return true; // allow form submission
}
</script>
Code.gs
(Server-Side Apps Script)function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
Put the HTML form in a file called Index.html
in your Apps Script project.
<form>
doesn't submit if validation fails.GIR 0AA
.