2

I want to change display format of text field input for Mobile number. Ex.

For number 1212121212, it should display (121) 212-1212 inside text and just for view purpose only. I also want full text on insert it into the DB. How can i achieve this in Angular 2 text input?

<p>How it is now</p>
<input type="text" value="1212121212" name="mobile"><br>
<p>How it should look</p>
<input type="text" value="(121) 212-1212" name="mobile2">

8
  • 1
    is this value always a fixed length? Commented Mar 22, 2018 at 10:01
  • Not sure. But can we try pattern for first 6 char? After '-' i don't care about length of numbers Commented Mar 22, 2018 at 10:02
  • checkout pipes in angular Commented Mar 22, 2018 at 10:03
  • @jai label is alright but what about input field? Commented Mar 22, 2018 at 10:07
  • 1
    Possible duplicate of Angular2 {pipes} - How to format a phone number? Commented Mar 22, 2018 at 10:16

1 Answer 1

4

You can do something like this with a pipe (just add a number at the end of the input).

I'm of course using a very simple regex, but you can create the one you want.

transform(value: string, args?: any): any {
  const regex: RegExp = new RegExp(/(\d{3})(\d{3})(\d{4})/);
  const match = value.match(regex);
  if(match) {
    return `(${match[1]})${match[2]}-${match[3]}`;
  } else {
    return value;
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

That's perfect. Just one question. Is it possible to start patterning from the first latter instead of 10 letters? Here after inserting 10 digits it is changing it's view.
Yes, that's what I told you, for that you will need a monstruous regex (or several little regexes).
as a piece of advice, if you use several little regexes, start with the biggest one, and finish with the simplest one. Otherwise, you might be surprised by the results you get.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.