I am trying to implement an exhaustive field formatting (here, of belgian phone numbers) while the user is typing.
Here is the code :
FormatZoneNumberOther: function (field, event, isGsm) { // +32 XX XX XX XX
console.log('FormatZoneNumberOther');
var authorisedValues = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'Backspace', 'Enter', 'Tab', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'],
keyValue = event.key; // string of the key pressed
if (field.value.length === 3 ||
field.value.length === 6 ||
field.value.length === 9 ||
field.value.length === 12 ||
field.value.length === 15) {
field.value += ' ';
}
if ((authorisedValues.indexOf(keyValue) === -1) && (keyValue !== '+') && (field.value.length !== 1)) event.preventDefault();
if (field.value.length > 14) {
event.preventDefault(); // prevent longer number than needed
checkZoneCode(field.value.substring(4, 7));
if (isGsm) {
alert('You have to insert a GSM number with format: +XX XX XX XX XX (FormatZoneNumberOther)');
return false;
}
}
},
The issue my client asked me to fix is when the end-user wants to modify one or several parts of the number: 01 234 55 67 89 => 01 222 55 67 89.
Obviously, the user would place the cursor with a mouse click or maybe with the arrow keys but this causes some issues as the validation is done based on the length of the field, which would then be longer than where the cursor is.
How can I improve this feature to take my client's request into account and also globally?
Thank you in advance,
PS: this has to be done in ES3 or JQuery 2.1.3 (maximum) and work on IE11 for reasons...
Edit1: I cannot use HTML5 input patterns for the same reasons. Edit2: I tried implementing a regex validation as it seemed promising, but I can't figure how to effectively test a changing string (as I type) with a fixed pattern. If it helps, when the user submits the field, my backend does the following test:
var pattern = /(+\d{2}){1}(46[0-1]|463|46[5-8]|47[0-9]|480|48[3-9]|49[0-9]){0,}(\d{2}){0,}(\d{2}){0,}(\d{2}){0,}/
So, my solution needs polishing, but I managed to completely go around my issues :
FormatZoneNumberGSM: function (field, event) { // +32 XX XX XX XX
},