Giter Club home page Giter Club logo

imaskjs's Introduction

imaskjs

vanilla javascript input mask

npm version License: MIT Coverage Status

Features

  • get and set raw and unmasked values easily
  • no external dependencies
  • supports overwrite mode
  • supports web components
  • supports contenteditable
  • RegExp mask
  • Function mask
  • Number mask (integer and decimal)
  • Date mask (various format support, autofix mode)
  • Dynamic/on-the-fly mask
  • Pattern mask
    • show placeholder always and only when necessary
    • unmasked value can contain fixed parts
    • optional input parts (greedy)
    • custom definitions
    • reusable blocks
    • secure text entry
    • Enum and Range masks
    • Repeating blocks
  • convert and format values with pipe

Plugins

Install

npm install imask and import IMask from 'imask';

or use CDN:

<script src="https://unpkg.com/imask"></script>

Build & Test

npm run make

Compatibility

Supports all major browsers. Can also be used with outdated browsers. See how

Getting help

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

imaskjs's People

Contributors

aleksandrjet avatar amerocu avatar ariasbros avatar armanio avatar artemgorev avatar b-legrand avatar chuuddo avatar danilowoz avatar dependabot[bot] avatar drifty17 avatar ejuo avatar firstvertex avatar i-welch avatar ivanov-v avatar leofavre avatar listepo-alterpost avatar lucas-maransaldi avatar marcobiedermann avatar monkeywithacupcake avatar mrmarble avatar nzacca avatar odrin avatar olafur-palsson avatar paulmaly avatar rjd22 avatar shackijj avatar siarhei-epam avatar unmanner avatar ustimov avatar virajnumino 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

imaskjs's Issues

[help] Currency mask

I've been trying to implement a currency filter for a bit now with no luck. Hoping that someone can direct me as I'm sure that I am missing something simple..

Need

I basically need the built in number mask with a prefixed $. And I would like it to work like a normal text mask ie user can type $32 and it's valid, but if they type just 32 the $ would be added automatically.

A string mask won't work as it's not flexible enough so I'm looking into the regex or function mask but haven't had much luck.

This regex will check for a valid currency:

// 1. '$' is optional
// 2. non-decimal currency is separated by commas ','
// 3. decimal is optional
// 4. if decimal exists, only two trailing numbers are allowed
// 5. leading zeros are not allowed

/(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$/

Note: using the above regex as my mask will allow `123` and `$123` but will not 
allow any more numbers, a comma or a decimal despite those being valid in the regex.

Implementation

I am building this in Angular but cannot use the provided Angular directive due to constraints I have for this project. To begin I have basically just copied the imaskjs Angular directive in my project (trying to get it working before adding my custom requirements).

I can't seem to find good examples of using a function mask. The only example in the guide shows a function just returning true/false. I was originally thinking that passing a Function to mask meant that the function should return a valid mask string. But as it's just returning a boolean, should I be adding my comma separators and $ in the prepare method I pass when creating the mask?

Can someone point me in a direction for this? 🙏

Example of how to use IMask without element

Some example of how to use IMask without DOM element is needed

Often we may need to convert some value to a formatted one. For example, a phone number. I get it from a DB and want to display to a user in a formatted style. How to do that by not involving real DOM input elements?

Last character of a datetime remains blank/masked

I'm having an issue where the last character of a datetime is being masked like this, and I can't type into the field any more:

screen shot 2018-01-02 at 13 34 47

I've created a JSFiddle that shows this in action. There's probably something wrong with the way my pattern is set up, but I couldn't work out what it is. Thanks in advance for any help you can give!

iOS problems

Can't get why mask isn't working on iPhones, any ideas?

bug with Date mask

There is a bug with Date mask even in your example. I can't fill all numbers in the year field(nope, it is not because the year is less than min or more than max)

Delete key not working when cursor is in front of thousands separator

If you use the Number mask and have configured a thousands separator, the delete key has no effect when the cursor is to the left of the separator, e.g. 1'000|'000 (pipe symbol is cursor). It's obvious, that the separator ' will not be deleted. But one would expect that the 0 right to the cursor would be deleted or that the cursor moves one to the right.

This works properly with other mask types but not with the number mask.

bug in ie11

Doesn't fire change event in ie11 while length of input more than length of mask. For example, mask: '+7 (000) 000-00-00' and I wrote 1 11+times

Can't import angular-imask

I updated angular-imask from 1.0.0 to 3.2.2 and got error:

Could not find a declaration file for module 'angular-imask'. '<path>/node_modules/angular-imask/dist/angular-imask.umd.js' implicitly has an 'any' type.
  Try `npm install @types/angular-imask` if it exists or add a new declaration (.d.ts) file containing `declare module 'angular-imask';`

Example in README of Vue plugin will not work as is

Example here: https://github.com/uNmAnNeR/imaskjs/blob/gh-pages/plugins/vue/README.md
will not work as is. In the top example (Mask Component Example) we need to write:

import {IMaskComponent} from 'vue-imask';

export default {
  // ...
  components: {
    MaskedInput: IMaskComponent
  }
}

Only in this case we will be able to use <masked-input/> tag in template.

Another variant:

import { IMaskComponent as MaskedInput } from 'vue-imask';

export default {
  // ...
  components: {
    MaskedInput
  }
}

I guess the same is valid for the bottom, directive example (I did not use directives in such way).

Number mask not applying to existing value onload

I'm using Angular version 5.2.5 and I have the following mask in my service.ts:

    public numericWithThousandsSeparator(max: number): {} {
        return {
            mask: Number,
            scale: 0,
            signed: false,
            thousandsSeparator: ",",
            padFractionalZeros: false,
            normalizeZeros: false,
            max: max,
            min: 0,
        };
    };

and my input looks like the folowing:

<input [imask]="this.maskService.numericWithThousandsSeparator(999999)" [unmask]="true" [(ngModel)]="thousandsMask" name="thousandsMask" />

and my component.ts defaults thousandsMask to a string = "1000"

public thousandsMask: string = "1000"; // would expect 1,000 to display in input field

However, on load of the page, 1000 is displayed in the input. I would expect 1,000 to be displayed. Is this a bug or intended?

I have a repo here that reproduces this: https://github.com/ryanbuening/imaskexample

trigger mask on existing values

How can i trigger the mask programmatically on a field that has already values filled in without doing .trigger('change')?

Warning to refresh

When I do imask.destroy() , clear the input value, do focus() and then I do another new IMask and right away I write, It throws this warning...

image

Change build config

to match future dev standards

  • remove es build
  • add new es2015 build as described here without polyfills and transpiling

А если на сайте несколько input?

У меня на сайте большое количество input, к которым необходимо прикрутить маску, как быть?
var phoneinput = document.getElementsByName('user-tel'); var phoneMask = new IMask(phoneinput, { mask: '+{7}(000)000-00-00', lazy: false, // make placeholder always visible placeholderChar: '_' // defaults to '_' });
Этот код не работает

Support for \p{L}

Hello,

I tried to use \p{L} expression that matches any kind of letter from any language.

It does seem to work with the following code:

new IMask(element, { mask : /^\p{L}+$/ });

I will appreciate some help here.

Thanks
Itay

date pattern

Все круто, но не смог поменять в паттерне даты места год и день
https://jsfiddle.net/corsik/1o6en3Lt/

Последний символ у года не печатается.
И еще подскажи пожалуйста, за что отвечает параметр Lazy?

Time (HH:MM) mask

Rather a help request then an issue. Need advice/example on implementing time mask.

The RegExp for 24-hour time format would be like:

/^([01]?\d|2[0-3]):[0-5]\d$/

I tried setting mask options like:

var maskOptions = {
    mask: 'HH{:}`MM',
    groups: {
        HH: {
            mask: '0[0]'
        },
        MM: {
            mask: '$0',
        }
    },
    definitions: {
        '$': /[0-5]/,
    }
};

, then updating mask pattern on-the-fly to validate hours properly (listening to accept event), but character shift didn’t work well.

Can anybody point me to the right direction please?

Thanks!

Third placeholder option

I think it might be useful to have an option to display mask placeholder only on focus.
Here an example:
asdadad

Date mask can reach state from which no valid date can be entered

(Please feel free to close this issue if you don't think it's a bug!)

To reproduce:

Expected behaviour: In this state, I wouldn't expect to be able to enter 2. After entering 2, any possible way of filling out the final digit of the year would result in a date after 31-12-2020.

Actual behaviour: I am able to enter 2. After entering 2, I can't enter a final digit.

React: hot to get value (masked or otherwise)

Hi everyone.

Sorry for bothering again, but I can't figure out how to get the value from the input field. I have it like this (changed a bit from last time):

this.inputField = <IMaskInput
    ref={(x) => { this.inputComponent = x; }}
    className='maskedInputStyle'
    mask={Number}
    unmask={true}
    placeholder={this.props.placeholder}
    thousandsSeparator={'\u2009'}
    padFractionalZeros={true}
    min={0}
    max={9999999999999.99}
    value={other.defaultValue + ''}
    {...other}
/>

I tried reading several combinations of properties but none returned the value. Also, I searched in Google and got a grand total of 3 results for IMaskInput, so I have no idea what to do.

Thanks in advance.

Angular unmaskedValue.replace is not a function

I'm using Angular 5.2.2 and angular-imask 1.0.2. I have the following service with various masks defined:

mask.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class MaskService {

    public alpha = {
        mask: /^[a-zA-Z]*$/
    };

    public alphaAllowSpaces = {
        mask: /^[a-zA-Z ]*$/
    };

    public alphaNumeric = {
        mask: /^[a-zA-Z0-9]*$/
    };

    public alphaNumericAllowSpaces = {
        mask: /^[a-zA-Z0-9 ]*$/
    };

    public numeric = {
        mask: /^[0-9]*$/
    };

    public phone = {
        mask: '(000) 000-0000',
    };

    public socialSecurity = {
        mask: '000-00-0000',
    };

    public fourDigitYear = {
        mask: Number,
        scale: 0,
        signed: false,
        thousandsSeparator: "",
        padFractionalZeros: false,
        normalizeZeros: false,
        max: (new Date()).getFullYear(),
        min: 0,
    };

    public numericWithThousandsSeparator(max: number): {} {
        return {
            mask: Number,
            scale: 0,
            signed: false,
            thousandsSeparator: ",",
            padFractionalZeros: false,
            normalizeZeros: false,
            max,
            min: 0,
        };
    }
}

and they are used in my HTML template:

<input class="form-control" name="constructionYear" [(ngModel)]="vm?.constructionYear" #constructionYear="ngModel"
                    required [imask]="this.maskService.fourDigitYear" minlength="4" />

All of the masks are working correctly when inputting values. However, when I save values and return back to my component to display the values I'm getting the following error(s):

ERROR Error: Uncaught (in promise): TypeError: unmaskedValue.replace is not a function TypeError: unmaskedValue.replace is not a function

None of the values get displayed in the inputs. Any ideas of what I could try?

Edit: I created an Angular CLI project that reproduces these examples here: https://github.com/ryanbuening/imaskexample

API docs

  • write custom html generator for documentationjs AST
  • styles

React: Number mask not respecting max value

Hi everyone.

I'm trying to use this library, but I can't get an input field to respect the max value I'm setting. I have something like this:

this.inputField = <IMaskInput
    className='maskedInputStyle'
    mask={Number}
    unmask={false}
    thousandsSeparator={'\u2009'}
    padFractionalZeros={true}
    min={0}
    max={99999999999999.99}
/>

I still can type much more digits than that. Is it a bug or am I using it wrong?

Thanks in advance.

Regex causes input to freeze

Using this regex

/^\+[0-9]\.\d{0,14}$/

causes the input to freeze. The example Russian postal code works fine. Is there something I'm missing in the regex for special chars? Thanks.

Angular ImaskJs

Привет

public ngOnInit() {
this.phoneMask = [
            {
                mask: '+{380} (00) 000-00-00',
                startsWith: '38',
                country: 'Украина',
            },
            {
                mask: '+{7} (000) 000-00-00',
                startsWith: '7',
                country: 'Россия',
            },
            {
                mask: '00000000000',
                startsWith: '',
                country: 'undefined'
            }
];
        this.superPhone = new IMask(document.getElementById('last_phone'), {
            mask: this.phoneMask,
            lazy: false,
            placeholderChar: '_',
            dispatch(appended, dynamicMasked) {
                let numbers = (dynamicMasked.value + appended).replace(/\D/g, '');
                return dynamicMasked.compiledMasks.find(function (m) {
                    return numbers.indexOf(m.startsWith) === 0;
                });
            }
        });
}

маска работает
и placeholder не отображается...(

если вывожу в разметке

<input type="text" name="phone" id="last_phone"
       formControlName="userPhone"
       [imask]="{
            mask: [
                {
                    mask: '+{380} (00) 000-00-00',
                    startsWith: '38',
                    country: 'Украина'
                },
                {
                    mask: '+{7} (000) 000-00-00',
                    startsWith: '7',
                    country: 'Россия'
                },
                {
                    mask: '00000000000',
                    startsWith: '',
                    country: 'undefined'
                }
            ],
            placeholderChar: '_',
            lazy: false
       }"
       class="ff-input"
       (focus)="focusTempString = 'userPhone'"
       (blur)="focusTempString = ''"
>

та же штука, тока маска странно работает

подскажите, что я делаю не так?

Autofill doesn't work properly on Chrome

Hi from Habr! Too low karma to comment there.

On Chrome 61, auto-filling works, but look at phone number in the following gif in your demo page:

auto-fill-bug 1

It formats with extra "7" in the phone field using auto-filling feature. Seems like a bug.

Didn't test this on other browsers as they don't matter for me.

Trigger elements with IMask

Hi, thanks for providing this cool plugin to make us easy for masking. I would like to ask, can I trigger elements with IMask. Example, in a page I have a form which contain 2 text field with behavior as year.

<form>
<label for="year"></label>
<input type="text" class="year" name="year" id="year">
<label for="taxYear"></label>
<input type="text" class="year" name="tax_year" id="taxYear">
</form>

When I initialize with IMask with the syntax below:

var yearMask = new IMask(document.getElementsByClassName("year"), options);

It doesn't work. Is that Imask doesn't support for multi elements? Thanks a lot

Integration with Vue

Hi! First, thanks for your excellent plugin.
I have strange behaviour for using your mask with Vue

IMask version:

"imask": "^3.1.2"

My input is:
<input type="text" class="form-control imask" data-mask="Date" data-mask-placeholder=" " required v-model="some-value" />

Mask options are very simple:

const maskOptions = {
	mask: IMask.MaskedDate
}

And input mask is not working :(
My input looks like this after successive pressing of the buttons from 1 to 9:

screen shot 2018-04-02 at 09 09 57

Many warnings in console with Uncontrolled input change, refresh mask manually! message

Unmask field based on select onChange event

I am using this plugin to mask a phone field.

What I am hoping to do is only have the mask apply if a user's country is the US. So if a user selects a country, which is not the US, in the dropdown, the mask will go away.

I am not exactly sure if using destroy() is the correct method or if I am even using it correctly, or if there is a better way to do this ...

This is my code:

`<script src="https://unpkg.com/imask"></script>

<script type="text/javascript"> document.addEventListener("DOMContentLoaded", function () { var phoneMask = new IMask(document.getElementById('billing:telephone'), { mask: '0000000000', lazy: false }); }); function resetPhone(CountryCode) { if(CountryCode !== "US") { var phoneMask = new IMask(document.getElementById('billing:telephone'), { mask: Number }); phoneMask.destroy(); } } </script>`

After I change the country and click in the phone field, when I start to type, I get this warning in Chrome:

input.js:181 Uncontrolled input change, refresh mask manually!
_saveSelection @ input.js:181
(anonymous) @ prototype.js?q=2018021301:391

Any suggestions would be great. Thanks for your help!

Prepare option throw an error

Prepare option throw an error link

pattern.js:249 Uncaught TypeError: Cannot read property 'length' of undefined
at MaskedPattern._append (pattern.js:249)
at MaskedPattern.resolve (base.js:104)
at MaskedPattern.set$$1 (base.js:98)
at InputMask.updateValue (input.js:191)
at new InputMask (input.js:74)
at new IMask (imask.js:25)
at window.onload ((index):48)

Alpha numeric pattern

Hi (@uNmAnNeR and @marcobiedermann) and thanks for this brilliant vanilla plugin; i have one question, maybe i missed something but, how do you set alpha numeric pattern ?
0 - any digit
a - any letter

    • any char
      ? - Alpha numeric ?

Thx.

Angular plugin

implement

  • ngAfterViewInit
  • ngOnChanges
  • ngOnDestroy
  • Output 'accept' and 'complete' events
  • crazy build stuff

[Question] Pass parameter from Angular Template to Mask?

I'm using Angular and have my input number mask setup as the following which is working great:

<input [imask]="numberWithCommas" [unmask]="true" />

public numberWithCommas = {
	mask: Number,
	scale: 0,
	signed: false,
	thousandsSeparator: ",",
	padFractionalZeros: false,
	normalizeZeros: false,
	max: 10000, // can this number be passed in?
	min: 0,
};

Is it possible to somehow setup the mask so that I could pass in different values for the max property? For example:

<input [imask]="numberWithCommas(999)" [unmask]="true" />

public numberWithCommas = {
	mask: Number,
	scale: 0,
	signed: false,
	thousandsSeparator: ",",
	padFractionalZeros: false,
	normalizeZeros: false,
	max: maxParameter, // can this number be passed in?
	min: 0,
};

Dynamic pattern groups

e.g.

var currencyInputMask = new IMask(element, {
  mask: '$num',
  groups: {
    num: {
      mask: Number  // ←- Currently only fixed-size string is available
    }
  }
});

Consider constrains:

  • only greedy
  • only for lazy mode (or fixed size placeholder?)

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.