We don't want our users to have to type the spaces and parenthesis but we do want the phone number field to display them once entered, ignoring them when typed. This is when we use the display patterns.
Because we also want our users to paste a formatted value into the field, including the spaces and parenthesis, we will start with a Text Field. If we used a Numeric Field then we won't be able to perform a paste, if the value contains anything but valid numeric characters then the whole paste would fail.
This means we must add some character filtering code to the change event so only digits are accepted. Filtering characters means testing xfa.event.change when the characters are coming one at a time, as they do when we are typing or, typically, testing xfa.event.newText when we are pasting a value.
But in this case we also want to set the maximum character limit to 10, this means the maximum length of xfa.event.newText is also set to 10 characters. This becomes a problem when the pasted value is formatted, in which case it will be either 12 or 14 characters. This is when we must use the xfa.event.fullText, which gives the full value before the truncation has occurred.
So our change event code now becomes;
xfa.event.change=(xfa.event.change.length > 1) ?
xfa.event.fullText.replace(/\D/g,""):xfa.event.change.replace(/\D/,"");
That is if the value causing the change is longer than one character, remove all non-digit characters, otherwise if the change is one character and that character is not a digit then ignore it.
xfa.event.fullText.replace(/\D/g,""):xfa.event.change.replace(/\D/,"");
The final part of our phone number field is to change the display pattern depending on which type of phone number has been entered, so our exit event code becomes;
var formatString = "";
if (!this.isNull)
{
if (LandLinePhoneNumberRegex.test(this.rawValue))
{
formatString = "'('99')' 9999 9999";
}
else
{
if (MobilePhoneRegex.test(this.rawValue))
{
formatString = "9999 999 999";
}
}
}
this.format.picture.value = formatString;
Setting a display pattern now means we can test for an invalid phone number using;
if (!this.isNull)
{
if (LandLinePhoneNumberRegex.test(this.rawValue))
{
formatString = "'('99')' 9999 9999";
}
else
{
if (MobilePhoneRegex.test(this.rawValue))
{
formatString = "9999 999 999";
}
}
}
this.format.picture.value = formatString;
TelephoneMobile.rawValue === TelephoneMobile.formattedValue
This works because the field will only be formatted when a value matches the display pattern, all other values are display as is and so the formatted value will equal the raw value.
Format strings with single quotes
If you ever want a single quote as part of the display pattern, as in a feet and inches measurement like 6'2" then you will need to use two single quotes and wrap then in single quotes. So four altogether,text{9''''9"}
No comments:
Post a Comment