I need to create an input in Aurelia that only accepts a phone number. If the user types 1234567890
into this input it should display (123) 456-7890
and the bound variable would be set to 1234567890
. The result should be the same if the user types (123) 456-7890
into the input as well. If the user types a letter into the input, the input should not display the letter, nor should the bound javascript variable get updated.
I'm able to partially achieve this using a ValueConverter:
phone.ts
export class PhoneValueConverter {
private removeNonDigits(input) {
let digits = '';
// Remove non-digits. i.e. '(', ')', ' ' and '-'
for (let i = 0; i < input.length; i++) {
let char = input.charAt(i);
if ('0' <= char && char <= '9')
digits += char;
}
return digits;
}
toView(value) {
if (!value)
return value;
value = this.removeNonDigits(value);
let formatted = '(' + value.substring(0, 3);
if (value.length >= 3)
formatted += ') ' + value.substring(3, 6);
if (value.length >= 6) {
// Don't place an upper limit, otherwise the user would not
// see the entire value
formatted += '-' + value.substring(6);
}
return formatted;
}
fromView(value) {
let digits = this.removeNonDigits(value);
// Only accept a 9-digit phone number
return digits.substring(0, 10);
}
}
app.html
<template>
${PhoneNumber} <br>
<require from="phone"></require>
<input value.bind="PhoneNumber | phone">
</template>
This works perfectly in forcing PhoneNumber
to always be 0-9 numerical digits. If the user types a letter, or a 10th digit, into the input, it will not be added to PhoneNumber
- just as expected. But unfortunately, the value of the input ($('input').value()
, not value.bind
) will still contain the extra, incorrect character.
Is there an Aurelia convention in controlling what characters get added to the value of the input?