Formatting Phone Number

classic Classic list List threaded Threaded
5 messages Options
Reply | Threaded
Open this post in threaded view
|

Formatting Phone Number

PotentialThymeleafUser

I have a phone number as a string in the format of nnn-nnn-nnnn and I need to display it as (nnn) nnn-nnnn

I tried searching how to do this with Thymeleaf, but have no luck.  Can someone point me in the right direction?
fiz
Reply | Threaded
Open this post in threaded view
|

Re: Formatting Phone Number

fiz
send to "view" array -> somthin like:

model.addAttribute("phone", "455-566-5555".split("-"));

and on "view"
th:text="'(' + ${phone[0]} + ') ' + ${phone[1]} + '-' + ${phone[2]}"
Reply | Threaded
Open this post in threaded view
|

Re: Formatting Phone Number

Emanuel
Administrator
In reply to this post by PotentialThymeleafUser
You could also create your own utility class with a method formatPhoneNumber() on it, that you can call from your template to do the formatting that fiz mentioned above:

<div th:text="${#myHelperClass.formatPhoneNumber(phoneNumber)}"></div>

Creating a utility class like that means creating your own dialect, so you might want to read up on that.  I don't think we have a tutorial in our documentation page for creating a dialect with just utility classes and methods, but I have a small project that you can look at for an example: https://github.com/ultraq/thymeleaf-joda-dialect  The key thing is creating a dialect that extends IExpressionEnhancingDialect.
Reply | Threaded
Open this post in threaded view
|

Re: Formatting Phone Number

bwfrieds
I like Emanuel's suggestion, but I did it slightly differently.  

Instead of a utility class, I added formatting methods to my biz pojo for more convenience.  The formatting method acts similar to a toString method.  For my app, that was a bit easier.

<div th:text="${obj.formatPhone()}"></div>

The tradeoff is, I cannot localize the formatting for my user's region.  My serverside code cannot see what region the user is in.  But I don't need that functionality.
Reply | Threaded
Open this post in threaded view
|

Re: Formatting Phone Number

mkobel
In reply to this post by PotentialThymeleafUser
I created an TagLib/ExpressionFactory using libphonenumber from Google. This could help you formatting the phone numbers in the national format.

Example:

https://www.kobelnet.ch/2020/01/08/formatting-phone-numbers-using-libphonenumber-in-thymeleaf

The source code is available on GitHub: itds-ch/phonenumber-thymeleaf-taglib