Skip to content

Instantly share code, notes, and snippets.

@kkiernan
Last active May 4, 2022 05:19
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save kkiernan/7475b615485344f2fdf3 to your computer and use it in GitHub Desktop.
Save kkiernan/7475b615485344f2fdf3 to your computer and use it in GitHub Desktop.
A Vue.js filter that formats a phone number.
<input type="text"
name="home_phone"
class="form-control"
v-model="homePhone | phone"
lazy>
/**
* Formats a phone number.
* Example: 123-456-7890 => (123) 456-7890
*
* @param {String} phone
* @return {Void}
*/
Vue.filter('phone', function (phone) {
return phone.replace(/[^0-9]/g, '')
.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
});
@kartsims
Copy link

Or there is vue-cleave

@pxwee5
Copy link

pxwee5 commented Jan 14, 2019

Wait, does this work? I didn't know v-model allows you to add filter like that in Vue2

@andreasvirkus
Copy link

@pxwee5 yup, they brought back filters for Vue 2.

@cbbov-rf
Copy link

cbbov-rf commented Jul 11, 2019

How would this work for two-way binding since that's been removed in 2.0?

I receive the following error and won't compile: SyntaxError: Assigning to rvalue

@ryantxr
Copy link

ryantxr commented Apr 13, 2020

filters don't work on v-model any more.

@andy3520
Copy link

Hi, is there any library support this kind of format?
text box

@AlanGreyjoy
Copy link

Just use vue-the-mask. v-mask="['(###) ###-###']"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment