vuejs-tips / vue-the-mask Goto Github PK
View Code? Open in Web Editor NEWTiny (<2k gzipped) and dependency free mask input for Vue.js
Home Page: https://vuejs-tips.github.io/vue-the-mask/
Tiny (<2k gzipped) and dependency free mask input for Vue.js
Home Page: https://vuejs-tips.github.io/vue-the-mask/
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
Any chances to use this as directive to integrate with UI frameworks such as vuetify?
Is there any way I can refresh the directive to reapply the mask?
Hi. Is there a possibility to show mask placeholder during input?
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
Why it's important?
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××) ×××-××-××"/>
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?
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.
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?
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
?
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
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?
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 },
//...
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。
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
Add ES Module build together with UMD build
Point to the .esm.js file in the package.json module
field
Like vue does https://vuejs.org/v2/guide/installation.html#Explanation-of-Different-Builds
It will lead to IDE better syntax highlighting and smaller bundle size because of tree-shaking
Olá, atualmente tem essa opção? Não consegui encontrar.
EX: Mask with Clear If Not Match Option do https://igorescobar.github.io/jQuery-Mask-Plugin/
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.
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?
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.
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
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?
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.
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 ?
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?
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
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.
This mask input breaks IE 11, won't let you enter anything into the forms.
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.
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) ### ## ##'
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);
}
});
For example, I don't want user to be able to type 99/99/9999 in Date of Birth. How to achieve that?
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
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.
When you publish the package to npm, you should include src
folder.
Benefits
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
?
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.
É possível capturar os eventos @blur
e @focus
no componente?
Exemplo
<the-mask mask="###.###.###-##" @blur="validaCpf" />
There is a way to use this like in the v-money component?
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.
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"/>
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
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."
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
Pretende adicionar mascara para moeda?
Assim ficaria completo!!!
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?
Good evening.
Is there any way to automatically clear the field when the mask is not completely filled?
In the jQuery Mask Plugin of Igor Escobar (https://github.com/igorescobar/jQuery-Mask-Plugin) there is the "clearIfNotMatch" option that does just that.
I need this option to "force" the user to fill in the data correctly because the field is accepting incomplete data.
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.