GithubHelp home page GithubHelp logo

vuejs-tips / vue-the-mask Goto Github PK

View Code? Open in Web Editor NEW
1.7K 1.7K 215.0 5.15 MB

Tiny (<2k gzipped) and dependency free mask input for Vue.js

Home Page: https://vuejs-tips.github.io/vue-the-mask/

JavaScript 63.99% Ruby 1.22% Vue 11.08% CSS 15.30% HTML 8.42%

vue-the-mask's Introduction

The Mask

A lightweight (2KB gzipped) and dependency free mask input created specific for Vue.js

The Mask Heart

Install

yarn add vue-the-mask
or
npm i -S vue-the-mask

Usage (two flavors)

Global

import VueTheMask from 'vue-the-mask'
Vue.use(VueTheMask)

Local (inside the component)

import {TheMask} from 'vue-the-mask'
export default {
  components: {TheMask}
}

Local (as directive)

import {mask} from 'vue-the-mask'
export default {
  directives: {mask}
}

Tokens

'#': {pattern: /\d/},
'X': {pattern: /[0-9a-zA-Z]/},
'S': {pattern: /[a-zA-Z]/},
'A': {pattern: /[a-zA-Z]/, transform: v => v.toLocaleUpperCase()},
'a': {pattern: /[a-zA-Z]/, transform: v => v.toLocaleLowerCase()},
'!': {escape: true}

The Mask Money

Properties

Property Required Type Default Description
value false String Input value or v-model
mask true String, Array Mask pattern
masked false Boolean false emit value with mask chars, default is raw
placeholder false String Same as html input
type false String 'text' Input type (email, tel, number, ...)
tokens false Object tokens Custom tokens for mask

What about money?

We understand that money format is a totally different domain, which needs another specific component. You can use https://github.com/vuejs-tips/v-money

The Mask Money

Other Solutions

  1. https://github.com/nosir/cleave.js https://github.com/nosir/cleave.js
  2. https://github.com/text-mask/text-mask https://github.com/text-mask/text-mask
  3. https://github.com/igorescobar/jQuery-Mask-Plugin https://github.com/igorescobar/jQuery-Mask-Plugin
  4. https://github.com/fernandofleury/vanilla-masker https://github.com/fernandofleury/vanilla-masker
  5. https://github.com/angular-ui/ui-mask https://github.com/angular-ui/ui-mask
  6. https://github.com/insin/inputmask-core https://github.com/insin/inputmask-core
  7. https://github.com/niksmr/vue-masked-input https://github.com/niksmr/vue-masked-input
  8. https://github.com/probil/v-mask https://github.com/probil/v-mask
  9. https://github.com/moip/awesome-mask https://github.com/moip/awesome-mask
  10. https://github.com/the-darc/string-mask https://github.com/the-darc/string-mask
  11. https://github.com/romulobrasil/PureMask.js https://github.com/romulobrasil/PureMask.js
  12. https://github.com/devindex/vue-mask https://github.com/devindex/vue-mask

Currency

  1. https://github.com/vuejs-tips/v-money https://github.com/vuejs-tips/v-money
  2. https://github.com/plentz/jquery-maskmoney https://github.com/plentz/jquery-maskmoney
  3. https://github.com/flaviosilveira/Jquery-Price-Format https://github.com/flaviosilveira/Jquery-Price-Format
  4. https://github.com/kevinongko/vue-numeric https://github.com/kevinongko/vue-numeric

Contribution

You're free to contribute to this project by submitting issues and/or pull requests. This project is test-driven, so keep in mind that every change and new feature should be covered by tests. Your name will be added to the hall of fame ;)

The Mask Wolf

License

This project is licensed under MIT License

vue-the-mask's People

Contributors

neumayr avatar neves avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-the-mask's Issues

v-mask directive array not working on v0.11.0-alpha.1

I'm trying to use the following, but it's not working:

<input type="text" name="phone" v-mask="['(##) ####-####', '(##) #####-####']" placeholder="{{ trans('front.phone') }}" />

I need to use the directive way because of the validator, but this v-mask array is just working on v0.10 that doesn't support the directive component.

vue events on the component

hey, I am trying to use this in a CEP field. The thing is I am trying to use the keyup event to fetch data from a restapi, but the event never happens. Is there a way to capture events using this component?

Another thing I've noticed is that there is no easy way of using validation plugins (such as vee-validate) with the field, this would be a nice improvement.

Regards,
João

mask is not exported in dist/vue-the-mask.js

Hello,

I'm using vue-the-mask 0.11.1. When importing the mask directive this way:

{mask} from "vue-the-mask";

I have this error:

Error: 'TheMask' is not exported by node_modules/vue-the-mask/dist/vue-the-mask.js

But if I use this import it works fine:

import {mask} from "vue-the-mask/src/index.js"; //force the use of src files

Is it the intended behavior or I am doing it wrong ?

No documentation on how to use custom tokens with directive

Hi

I could not find how to use custom tokens with the directive.

Edit: Watching how its done in the component I figured it out, but adding it to the documentation could save time to others in the future.

You just need to pass an object to the v-mask

<input type="tel" v-mask="{mask: '+7 (F##) ###-##-##', tokens: hexTokens}" v-model="phone"/>

You could also define it as an object

data () {
    customMask: {
      mask: '+7 (F##) ###-##-##',
      tokens: 
        'F': {
          pattern: /(?!8)\d/
        },
        '#': {pattern: /\d/}
      }
    }
  }
<input type="tel" v-mask="customMask" v-model="phone"/>

the cursor jump to end position when edit the front of typed text

my code:

//html
      <the-mask v-model="form.mac" type="text" mask="FF:FF:FF:FF:FF:FF" :tokens="hexTokens" class="el-input__inner" placeholder="仅支持16进制字符"></the-mask>

//js
      hexTokens: {
        F: {
          pattern: /[0-9a-fA-F]/,
          transform: v => v.toLocaleUpperCase()
        }
      },

I input 'AA:AA:AA:AA:AA:AA' ,it's ok,
i want to change it to 'AA:BB:AA:AA:AA:AA'
i move the cursor, delete the second AA, and input a B, then the cursor jump to the end
i can not input 2 BB continuously。

Error in callback for watcher "value"

I have a master-detail view and a number of the fields are initially null. The first time an instance encounters null values based on the underlying v-model I get the following:

TypeError: Cannot read property 'substring' of null
    at VueComponent.refresh (vue-the-mask.js:141)
    at VueComponent.boundFn [as refresh] (vue.esm.js:124)
    at VueComponent.value (vue-the-mask.js:113)
    at Watcher.run (vue.esm.js:2551)
    at flushSchedulerQueue (vue.esm.js:2329)
    at Array.<anonymous> (vue.esm.js:505)
    at nextTickHandler (vue.esm.js:454)
    at <anonymous>

The line in question is

var r = t.substring(0, e);

The errors don't occur subsequent times because the control sets the value to ''. Changing line 141 to the following seemed to fix my particular issue but I did not run the fix through a battery of regression tests.

var r = t === null ? '' : t.substring(0, e);

Regards,

Greg

Using mask show numerical keyboard under mobile issue

Hello,

I cannot seem to make the credit card mask work if the (type="number") is set on the tag.
Setting this forces mobile browsers to show the numerical keyboard.

Is there another way to do this??
Thanks
Christian

Usage in non input elements

Hi,

How are you applying masks to those <span> elements in the docs page placed right of the inputs in the first section? With plain js regex?
The docs codebase is available somewhere so I can check it?

Thanks

No documentation about using functions in mask property

I was trying to use a function in the mask property but the documentation don't explain the correct way to do it, so the result it is not the expected. Would be great improvement to documentation specify as to use functions in mask property.

Can't mask AMEX

Hi. Thanks for cool plugin!

I can't find a way to mask American Express and Visa simultaneously.
It has this format xxxx xxxxxx xxxxx.

I thought it could be cool if I could detect some conditional values and use proper mask. For example, if string begins with 37 (AMEX staring numbers), then use one mask, if not then another.

Will appreciate any thought, how it can be done.

v-on:keyup não é acionado

Estou noobando aqui quando tento o seguinte trecho de código

<the-mask :mask="'#####-###'" v-model="cep" @keyup="buscar"/>

Tudo aparenta funcionar normalmente e perfeitamente, exceto o evento keyup que não aciona a função buscar() onde realizo uma busca num webservice para autocompletar os outros campos de endereço.

Masking words

I want to create a mask so that the user can input twelve random words. any idea on how to make it with vue-the-mask ?

Use :state with masked input?

I cant figure how to use the ":state" property with this maked field.
If it is not supported, can anyone tell me the css class needed to get ":state=false" effect?

Thank you

caret jumps backwards

I tried to create a mask for numbers with dots as thousands-separator. My mask is in the array-format, and I figured out that each mask entry needs be exactly one character longer:

    [
       '###',
        '####', // workaround to prevent '1.11'
        '#.###',
        '##.###',
        '###.###',
        '####.###', // workaround to prevent '1.000.00'
        '#.###.###',
        '##.###.###',
    ]

The mask itself works fine so far, but if the same character is entered repeatedly, the caret will not end up at the end but move one or two spaces backwards. This seems to happen when the two workaround mask entries are jumped over. If different numbers are entered, the caret stays at the end as intended.

Here is where the caret ends up:

1.0|0
10.000.0|00

Capturar evento @blur e @focus

É possível capturar os eventos @blur e @focus no componente?

Exemplo

<the-mask mask="###.###.###-##" @blur="validaCpf" />

Selector Bug on Android

When using vue-the-mask as a directive like so:

<input type="tel" name="credit-card" v-mask="#### #### #### ####">

On Android, after having entered the first 4 numbers, when I enter the 5th the cursor shift in position before the last number entered. Example:

1234 |5

I see this bug persist in pretty much all the mask plugins I have tried so far, is there any plan to solve this for vue-the-mask?

Can't use empty mask

I have my own text-field component, and a mask option is optional.
I use a prop in combination with vue-the-mask directive.
The prop in my component is defined like: props: { mask: { required: false, default: '' } }
The problem is that vue-the-mask enforces the field to be literally empty so the input is unusable.
Is there a way around this?

Problema com máscara de telefone

Olá,

Estou utilizando o exemplo:

<input v-mask='["(##)####-####", "(##)#####-####"]' v-model="fieldValue" type="text" :name="name" />

Ao carregar o campo em branco o componente acaba preenchendo com o início da máscara: "("

No caso, carrego vazio mas o value fica: "("

Podem me ajudar?

Include src with package

When you publish the package to npm, you should include src folder.

Benefits

  • One can go and check the implementation within node_modules
  • Easy to debug
  • Custom build

Dynamic mask when using directive?

Hi, thanks for the great library!

I'm using the directive form (since I'm using 3rd party UI components) and everything works great when I hardcode the mask (i.e. v-mask="'+1 (###) ###-####'") but I can't get it to work when trying to bind to instance data (i.e. :v-mask="phoneMask").

When inspecting I can see Vue binds the instance data to the element but it doesn't seem to be picked up by vue-the-mask as the on_input event listener is not created.

I was hoping to be able to dynamically change the mask depending on which country the user selects by changing the instance value of phoneMask on the fly, is there any way to do it?

Dynamic mask not working

I'm trying to add this dynamic mask:

['########-#', '##########-#'] so a user can type 14523259-9 and 1012325456-9 but the lib applies only the first mask and I can't type any further.

Any thoughts?

Is it Possible to apply the mask when the condition is met?

Wondering if you already have an option to get the mask applied when the condition is met
Per example lets say the mask is (###-##)
So basically the expected behavior is that when I type 3 digits i have to get - automatically and not until I type the 4th digit.

Caret position

In US phone example: +1 (###) ###-####
If I start to type 1 in a clear input, visible value becomes +1. But caret sets after + and before 1.
If next I type 9, visible input becomes +1(91

So typing 19 in clear input leads to+1(91, I think it should lead to +1(9

How to use that programmatically?

I have my component:

const vm = new Vue({
    el: '#FormVue',
    directives: {mask},
    validator: null,
    data() {
        return Object.assign({
            name: '',
            email: '',
            errors: null
        }, $_POST);
    }
});

How to use mask without directive?
Example:

const vm = new Vue({
    el: '#FormVue',
    directives: {mask},
    validator: null,
    data() {
        return Object.assign({
            phone: {mask: '####-####'},
            cpf: {mask: '###.###.###-##'},
            errors: null
        }, $_POST);
    }
});

Question: custom directive pattern

Great package! I see that you can create custom tokens for the component implementation, but using as a directive, am I able to add custom tokens or patterns in some way? For instance, I was trying to enforce digits, but allow for any number of them. I was trying things like v-mask="{pattern: /[0-9]+/}" just to see if I could, ha.

Thanks,
Paul

Máscaras para Agência e Conta bancárias

Bom dia,

Acho que achei um bug nas máscaras, veja as máscaras que criei:

Agência: :mask="['####', '####-#', '####-##']"
Conta: :mask="['#####-#', '######-#', '#######-#', '########-#', '#########-#', '###########-#']"

No caso da agência, a máscara só adiciona um dígido após o traço., Ou seja, só '####', '####-#', funcionam.
Já para a conta, só '#####-#', '######-#', funcionam.
Em ambos os casos não é possível adicionar mais dígitos além dessas máscaras que funcionaram.

Pode me dar uma ajudinha com isso? Será que fiz algo errado ou é alguma limitação da biblioteca?

Grato.

Ignore user typed the same char in mask

Is that possible to ignore user typed the same char in mask?
My mask is v-mask="'+7 (###) ### ## ##'"
When user types '708' it just fills '+7 (08#) ### ## ##' but goal is to fill '+7 (708) ### ## ##'

e.component not a function?

Im trying to use this in my component to mask mm:ss and transform numeric input automagically. I installed with npm i -S vue-the-mask:

+ [email protected]
added 114 packages and updated 1 package in 22.598s

then I edited my component:

<template>
  <masked-input name="scene_length" mask="##:##" :masked="true" type="text" class="form-control" placeholder="mm:ss" v-model="newScene.duration">
    </masked-input>
<!-- ... -->
<script>
import TheMask from 'vue-the-mask'
//...
export default {
  components: { 'masked-input': TheMask },
//...

That produces this error:

vue.esm.js:479 [Vue warn]: Error in render function: "TypeError: e.component is not a function"

found in

---> <AddScene> at C:\Users\roberto\Qwire\github\dev2\qwireclear-frontend\src\components\wbf\scene\scenes_overview\AddScene.vue
       <ScenesOverview> at C:\Users\roberto\Qwire\github\dev2\qwireclear-frontend\src\components\wbf\scene\ScenesOverview.vue
         <App> at C:\Users\roberto\Qwire\github\dev2\qwireclear-frontend\src\components\App.vue
           <Root>
warn @ vue.esm.js:479
handleError @ vue.esm.js:562
Vue._render @ vue.esm.js:4130
updateComponent @ vue.esm.js:2538
get @ vue.esm.js:2881
Watcher @ vue.esm.js:2870
mountComponent @ vue.esm.js:2542
Vue$3.$mount @ vue.esm.js:7863
Vue$3.$mount @ vue.esm.js:10066
init @ vue.esm.js:3501
createComponent @ vue.esm.js:5147
createElm @ vue.esm.js:5090
patch @ vue.esm.js:5606
Vue._update @ vue.esm.js:2424
updateComponent @ vue.esm.js:2538
get @ vue.esm.js:2881
run @ vue.esm.js:2958
flushSchedulerQueue @ vue.esm.js:2724
(anonymous) @ vue.esm.js:701
nextTickHandler @ vue.esm.js:648
vue.esm.js:566 TypeError: e.component is not a function
    at r (vue-the-mask.js:1)
    at resolveAsyncComponent (vue.esm.js:2109)
    at createComponent (vue.esm.js:3587)
    at _createElement (vue.esm.js:3797)
    at createElement (vue.esm.js:3736)
    at vm._c (vue.esm.js:4076)
    at Proxy.render (AddScene.vue?6af9:79)
    at VueComponent.Vue._render (vue.esm.js:4128)
    at VueComponent.updateComponent (vue.esm.js:2538)
    at Watcher.get (vue.esm.js:2881)

If I go on to change to the directive form it works:

<template>
  <input name="scene_length" v-mask="'##:##'" :masked="true" type="text" class="form-control" placeholder="mm:ss" v-model="newScene.duration">
    </input>
<!-- ... -->
<script>
import { mask } from 'vue-the-mask'
//...
export default {
  directives: { mask },
//...

Problema ao inicializar / Failed to mount component

Olá pessoal,

Gostei muito do componente, é o que eu estava procurando, Mas estou com problemas pra usá-lo. Fiz o seguinte:

Baixei o pacote das duas formas:
npm i -S vue-the-mask
npm install vue-the-mask --save-dev

Na minha página/componente Vue:

<the-mask
	:type="'text'" ref="input"
	:mask="['###.###.###-##', '##.###.###/####-##']"
	placeholder="CPF / CNPJ">
</the-mask>
<script>
import TheMask from 'vue-the-mask';

export default {
	components: { TheMask },
	data() {
	...

Mas aparece o seguinte erro no console:

[Vue warn]: Failed to mount component: template or render function not defined.
(found in )

Estou fazendo algo de errado? Testei no JsFiddle e funcionou certinho, mas na minha aplicação tenho o tal erro. Estranho, pois tenho alguns componentes que criei e funcionam perfeitamente.

Outra dúvida que tenho é: ele suporta outros atributos do input, como id, class, autocomplete para serem setados por v-bind?

Agradeço.

$event target not set proverly

If you do <the-mask @input="handler"></the-mask>

handler ($event) {
 // $event here should be an instance of Event
}

The argument passed to the handler is the actual value of the input. It should be an instance of Event so you can access the target and its properties. I'll see if I can PR this when I get some time.

Mask breaks on mobile

Chrome mobile seems to break some behavior when setting the cursor.

With mask AAA-####, when you start typing the letters and will type the first number, the cursor is here ( | ): ABC-|6, where it should be here: ABC-6|.

Tested on latest Chrome mobile @ Android 7

Evento @blur

Olá, não estou consiguindo realizar o evento blur utilizando este componente, segue o codigo.
<the-mask :mask="['#####-###']" @blur="buscarCep" class="input" v-model="endereco.cep" v-bind:class="{ 'input is-danger' : enderecoErros.cep }" />

Poderia me ajudar?

Bug - the blur event is not fired

I am using the version 0.11.1. When I subscribe to the onBlur event on the mask input, the blur event is not fired.
e.g.

<the-mask v-model="phone" class="form-control" mask="####" @blur="onBlur"></the-mask>

I would expect the onBlur function is executed when the focus moves away from he input, but that does not happen.

Usage as directive

Any chances to use this as directive to integrate with UI frameworks such as vuetify?

Focus component input

It doesn't seem like it's currently very easy to focus the input when using the-mask component, what do you think about adding a focus method for this?

Vuex Warning

Hi! I'm getting this warning when I import the component into my project:

[Vue warn]: Error in callback for watcher "function () { return this._data.$$state }": "Error: [vuex] Do not mutate vuex store state outside mutation handlers."

Raw output is not working

I want to output raw data, like in example, but this is not working

<input v-model="phone" masked="false" v-mask="'+38 (0##) ###-##-##'" placeholder="+38 (0××) ×××-××-××"/>

Mascara input celular

Ola, estou tendo um problema ao usar a mascara no celular.

Estou usando o seguinte codigo
<the-mask mask="AAA-####" v-model="placa" placeholder="AAA-0000"></the-mask>

No computador funciona perfeitamente, porem quando testo no celular acontece um problema.

Quando vou digitar o primeiro numero da placa o caret fica antes do numero.

Assim: ABC-|1

Isso acaba sendo um problema de usabilidade porq o usuario vai digitar direto e a placa fica errada

Custom tokens

Hi.

It's possible to use custom tokens with v-mask directive?

also i need mask number which either can be negative -10 or positive 10. is it possible to do?

Moeda

Pretende adicionar mascara para moeda?
Assim ficaria completo!!!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.