Auto Input Validation Form Fields

The JS
The CSS
Last updated
Was this helpful?

Last updated
Was this helpful?
Was this helpful?
// The example is used for the 'XXX XX XXXX' input only
$(document).on('knack-view-render.any', function (event, view, data) {
$('input#field_XXX').keyup(function(event) { // When inputting the field
this.value = this.value.replace(/[-]/g, ''); // replace hyphens with nothing
if (event.key === 'Backspace') { // ignore if backspace
return;
} else if (event.key === ' ') { // reject " "
this.value = this.value.replace(/[\s]/g, ''); // replace space with nothing
} else if (isNaN(Number(event.key))) { // if not number
this.value = this.value.replace(/[^0-9\s-]+/g, '');
}
// Auto adds spacing at 4th and 7th position.
if (this.value.charAt(3) != " "){ // replace if no space at 4th position
this.value = this.value.replace(/^(.{3})(.*)$/, "$1 $2");
}
if (this.value.charAt(6) != " "){ // replace if no spaces at 7th position
this.value = this.value.replace(/^(.{6})(.*)$/, "$1 $2");
}
});
$("input#field_XXX").attr('maxlength', 11); // Max input 11 characters
$("input#field_XXX").attr('placeholder',"___ __ ____");
});