Expand my Community achievements bar.

Please help: Custom pattern for phone numbers.

Avatar

Former Community Member
This is the display pattern I have so far:

text{'775'-999-9999}|text{999-999-9999}



It turns 9999999 into 775-999-9999 and 9999999999 in 999-999-9999



What I need help with is turning (999)999-9999 into 999-999-9999.



Can't seem to automatically get rid of the parenthesis and/or convert to only dashes. I've tried various javascript and formcalc in the script editor but nothing seems to work.



Can someone please help?



Thank you.
4 Replies

Avatar

Former Community Member
Hi Micheal,

You can convert the vaue entered with the replacement of new value which can be generated by a regular expression replacement. To the exit event of component, write a javascript which runs at client.

First, create a regular expression (can learn how to create regular expressions from site http://www.webreference.com/js/column5/index.html). This regular expression matches a single '(' at the beginning '\(?' and 3 digits

\d{3} and a closing parenthesis '\)?'.

Then, replace the value of the component with the specified 3 digist and a '-', $1-. $1 is the matching digits enclosed by parenthesis '(\d{3})'.

Lastly, set the resulting replacement back to component value.

This is the full script you can use.



re = /\(?(\d{3})\)?/;

val = this.rawValue;

result = this.rawValue.replace(re, "$1-"); // replace the match of regular expression with (\d{3}) three digits

this.rawValue = result; // set result back to component



Hope it helps and not so complicated. With regular expressions you can do many other replacements, checks.

Asiye

Avatar

Former Community Member
Awesome! This worked!



Just one little bug though. If for some strange reason the user tabs/clicks back into the field then tabs/clicks back out, the field inserts an extra hyphen each time. Not usually a problem and I could always make the field equal "" when the user tabs/clicks back in. But I would rather not do that. Any suggestions for this?



Thanks.

Avatar

Former Community Member
It is because of missing check of the existance, you can add a check if ")" is entered or create another check to about your case. Script can be:



re = /\(?(\d{3})\)?/;

val = this.rawValue;

if(val.indexOf(")") > -1){

result = val.replace(re, "$1-"); // replace the match of regular expression with (\d{3}) three digits

this.rawValue = result; // set result back to component

}



Asiye

Avatar

Former Community Member
Hmm, what's strange is that I tried this yesterday and it did not work. Must've been a typo in my if statement or something. Pasting yours in the script editor worked.



Thank you VERY much, Asiye. My boss and coworkers are happy now.