Giter VIP home page Giter VIP logo

react-maskedinput's Introduction

MaskedInput

A React component for <input> masking, built on top of inputmask-core.

This project has never been used by its author, other than while making it.

Install

npm

npm install react-maskedinput --save

Browser bundle

The browser bundle exposes a global MaskedInput variable and expects to find a global React variable to work with.

Usage

Give MaskedInput a mask and an onChange callback:

import React from 'react'
import MaskedInput from 'react-maskedinput'

class CreditCardDetails extends React.Component {
  state = {
    card: '',
    expiry: '',
    ccv: ''
  }

  _onChange = (e) => {
    this.setState({[e.target.name]: e.target.value})
  }

  render() {
    return <div className="CreditCardDetails">
      <label>
        Card Number:{' '}
        <MaskedInput mask="1111 1111 1111 1111" name="card" size="20" onChange={this._onChange}/>
      </label>
      <label>
        Expiry Date:{' '}
        <MaskedInput mask="11/1111" name="expiry" placeholder="mm/yyyy" onChange={this._onChange}/>
      </label>
      <label>
        CCV:{' '}
        <MaskedInput mask="111" name="ccv" onChange={this._onChange}/>
      </label>
    </div>
  }
}

Create some wrapper components if you have a masking configuration which will be reused:

function CustomInput(props) {
  return <MaskedInput
    mask="1111-WW-11"
    placeholder="1234-WW-12"
    size="11"
    {...props}
    formatCharacters={{
      'W': {
        validate(char) { return /\w/.test(char ) },
        transform(char) { return char.toUpperCase() }
      }
    }}
  />
}

Props

mask : string

The masking pattern to be applied to the <input>.

See the inputmask-core docs for supported formatting characters.

onChange : (event: SyntheticEvent) => any

A callback which will be called any time the mask's value changes.

This will be passed a SyntheticEvent with the input accessible via event.target as usual.

Note: this component currently calls onChange directly, it does not generate an onChange event which will bubble up like a regular <input> component, so you must pass an onChange if you want to get a value back out.

formatCharacters: Object

Customised format character definitions for use in the pattern.

See the inputmask-core docs for details of the structure of this object.

placeholderChar: string

Customised placeholder character used to fill in editable parts of the pattern.

See the inputmask-core docs for details.

value : string

A default value for the mask.

placeholder : string

A default placeholder will be generated from the mask's pattern, but you can pass a placeholder prop to provide your own.

size : number | string

By default, the rendered <input>'s size will be the length of the pattern, but you can pass a size prop to override this.

Other props

Any other props passed in will be passed as props to the rendered <input>, except for the following, which are managed by the component:

  • maxLength - will always be equal to the pattern's .length
  • onKeyDown, onKeyPress & onPaste - will each trigger a call to onChange when necessary

MIT Licensed

react-maskedinput's People

Contributors

aesopwolf avatar alexeybondarenko avatar ar7n avatar avindra avatar bernardofbbraga avatar bpugh avatar dwbruhn avatar heymdall avatar hunterc avatar iamdustan avatar insin avatar jcobbsk avatar jquense avatar martyphee avatar muffinresearch avatar nathanstitt avatar npmcdn-to-unpkg-bot avatar thorarin avatar vslinko 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

react-maskedinput's Issues

pass through pattern prop

Not sure what to do here.

Here's my use case:

  • Credit card input
  • Pattern is '1111 1111 1111 1111'
  • Want keyboard that pops up to be a numeric keyboard, since the only editable characters are numbers

With a normal input you would pass a pattern of [0-9]* to the input and it will show a numeric keyboard on ios on android. Since react-maskedinput already uses this key, there is no way to do this.

Either need a way to pass this through, or better yet maybe maskedinput could pass the regex pattern through itself so the OS can show the correct keyboard

Doesn't work in Mobile Internet Explorer

From what I've read Mobile Internet Explorer doesn't support the onKeyPress event, which is breaking this implementation. I've looked at the open pull request for android (#47) and was able to make a working version that supports Android as well as browsers that support onKeyPress, by doing this:

    var event = {};
    if (!userAgent.match(/Android/i)) event.onKeyPress = this._onKeyPress;
    else event.onBeforeInput = this._onKeyPress;
    return (
      <input
        {...the_rest}
        ref={r => this.input = r }
        onChange={this._onChange}
        onKeyDown={this._onKeyDown}
        onPaste={this._onPaste}
        {...event}
        placeholder={this.props.placeholder}
        value={this._getDisplayValue()}
      />
    );

I wish there was some feature detection for onkeypress support or onbeforeinput support... any ideas anyone?
This works great for Android, but I also found that Mobile Internet Explorer wasn't working. I tried all kinds of ways to bind the functions in this env, but it came down to this. Most browsers fire events in this order from a keyboard input (key down -> key press -> before input -> input -> key up). But Mobile IE does this: (key down -> key up -> input) NOTE: no keypress and the input is post key up and no before input. Anyway, I hope this helps someone, but I wasn't able to quite get it to work on Mobile IE. For now I fall back to unmasked inputs for Mobile IE, but I'd really like to fix this if possible.

Mask doesnt not work on Android Chrome

Look that:

Mask Bug

Any idea of how to solve that?

Demo env:

package.json

  "dependencies": {
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "react-maskedinput": "^3.3.4"
  }

App.js

var React = require('react')
var MaskedInput = require('react-maskedinput')

var CreditCardDetails = React.createClass({
  state: {
    card: '',
    expiry: '',
    ccv: ''
  },

  _onChange(e) {
    var stateChange = {}
    stateChange[e.target.name] = e.target.value
    this.setState(stateChange)
  },

  render() {
    return <div className="CreditCardDetails">
      <label>
        Card Number:{' '}
        <MaskedInput mask="1111 1111 1111 1111" name="card" size="20" onChange={this._onChange}/>
      </label>
      <label>
        Expiry Date:{' '}
        <MaskedInput mask="11/1111" name="expiry" placeholder="mm/yyyy" onChange={this._onChange}/>
      </label>
      <label>
        CCV:{' '}
        <MaskedInput mask="111" name="ccv" onChange={this._onChange}/>
      </label>
    </div>
  }
})
export default CreditCardDetails

Dynamically Changing Mask forces cursor to end of placeholder value

When dynamically changing the mask based on initial input like for Credit Card mask needs to be adjusted if 34 or 37 is typed in because those are amex "1111 111111 11111", the mask gets adjusted appropriately, but the cursor is placed at the end of the placeholder "_"s so the user can't keep typing the rest of the number without manually moving the cursor.

Is there a prop or callback I can use to override this behavior?

Get raw value of input

HI,

I am able to get the value of the input using the onChange function and via even.target.value (as per documentation). However the value contains the mask characters as well. Is there any way to get the raw value?

Edit value programmatically

Is it possible to edit a value programmatically?

e.g. for a default input-field you just need to edit its value-attribute, but for a maskedinput, the value is only used as a default-value.

update the pattern does not chanage the value correctly.

let't say the value is 123456 and the pattern is 111111.
the input mask will show all the numbers and it works perfectly!
if I change mask to 111 the input mask will show 123 which is correct. but if I change the mask back to 11111 it will show 123__ !!!!!!
However the value is not changed and even I provide the correct value (123456) again but since the value has not changed it ignores it!!!
you can see it here: http://insin.github.io/react-maskedinput/

I would appreciate any help

Pass value to formatCharacters validate

How about passing input value to validate method in formatCharacters. I think it will be convenient.
Example

<MaskedInput
  formatCharacters={{
    'w': {
      validate(char, value) {
        return value.length === 1 && char === 'w' || value.length === 2 && char === 'W';
      },
    }
  }}
/>

This example does not make sense, but this functional can be useful.

Incompatibility with react 15.4.0

React 15.4.0 has been released which removes a lot of the internals, specifically around ReactInputSelection which causes 3.3.0 to break. Saw this had been remedied in the latest commits though.

It would be good to get this released soon as it's likely a lot of people will be upgrading in the next few days.

Thanks ๐Ÿ‘

Add "enable mask on focus" feature

Currently the mask is always enabled. It would be nice to have the mask only show up "onFocus". Would be cool to have "unFocusedPlaceholder".

e.g. unFocusedPlaceholder here is "Phone Number"
maskonfocus

[Mobile Chrome] Does not respond to onKeyUp to get keycode

hi all,

I have been using this package for a while and its been working until of late. onKeyUp used to give me the event.keyCode for all browsers including Mobile Chrome. Then all of sudden it stopped working for that browser, just wanted to know if anyone else is having this issue too.

thanx

Make value property consistent with React

value should be changed to defaultValue to make this consistent with React inputs. Currently, react-maskedinput's value property behaves identical to React's defaultValue input property.

value should also reflect any changes made. Similar to how React handles value on input components.

HowTo: getRawValue() "inputmask-core already exposes this"

Hello,

How to extract rawValue from MaskedInput as from the source it looks like e.target.value is being set with displayValue.
Requirement is to get RawValue and not the current value which contains the place-holders too.

Thanks!

Add tests

After #20 it might be nice to stand-up some tests with karma-webpack or similar - this will probably help reduce the maintenance overhead and make dealing with PRs a little easier.

React.PropTypes warning

I'm getting the following error in my console:

screen shot 2016-08-31 at 2 30 30 pm

My current version of React is ^15.1.0. Let me know if you need any more details.

Component doesn't submit in mozilla firefox

Masked input doesn't submit when I run my application in Firefox. The problem ocurr when I try to submit my form pressing enter in the masked field. I think that is because:

In function onKeyPress it has

if (e.metaKey || e.altKey || e.ctrlKey || e.key === 'Enter') {
return;
}

but the key is NULL when I press enter in the field, then

e.preventDefault() stop my submit.

Mask doesn't update if value is changed.

I have a simple case:
At first, the {value} of my masked input is undefined.
Component then assumes this is starting value and sets it up as such.
However, from this moment onward, masked input will only react to user input, and will ignore any subsequent changes made via altering the value prop.
Is there any way to avoid this behavior, other than hiding the input until value is actually defined (which I can't do for reasons outside this discussion)?

Using regular expression to define masks

Firstly I have to say I love the package. The method of defining mask is rather limited. I would like to suggest that you use regular expressions to define the input masks. Yes I do know that JavaScript regular expression, although very fast and powerful does not have the capability that is required.

Your package inspired me to help you out with that. This use case needs a somewhat different api and capability in regular expressions:

  1. Incremental processing - that is, regular expression what checks against part of the string
  2. Lets you know the state of the match
    • DONE - the entire expression has been patched
    • MORE - the match is incomplete and requires more input
    • MAYBE - the mach is complete but will take more input
  3. It will generate a mask for the remaining characters in the input
  4. Support most if not all the capabilities of JavaScript regular expression

I am in the process of creating such a package. I have written the initial version and it is passing all the tests that I have; but I cannot say that it is complete.

Incremental Regular Expression

I have still work to do making it into a full node package. Please have a look and specially at the test that I have. Currently I am passing all my 80 or so tests; but clearly this is far from exhaustive.

main field in package.json is wrong

Currently trying to npm i insin/react-maskedinput (install straight from github since the npm package is out of date) results in a broken package in my node_modules: main in package.json points to ./lib/index.js and the only folder available is dist.
You should point the main to dist/react-maskedinput.js

How to reject invalid times?

I am using this for a time input with a mask of 11:11. However, not all digits are ok for a time. Hours over 23 and minutes over 59 should be prohibited.
I have my component which wraps react-maskedinput but that only has access to onChange to read the entered value. How can I reject 3_:__ right away (as soon as the user types 3 for the hour, I know it's wrong) or 27:__ or 14:8_.
I cannot stop this from onKeyDown (as I believe it should be done) as it's not available. I was thinking you should allow props.onKeyDown, call it first in your _onKeyDown() and skip the rest of the function if props.onKeyDown() returns false (or if e.isDefaultPrevented() maybe). This way you allow the users to reject keypresses based on their own logic.

I can send a PR if this sounds ok but I wanted to hear from you first - maybe there's an easier way to do the above that I missed?

Pattern changes are not immediately reflected

For things like credit cards the pattern needs to be updated on the fly. E.g. if an amex card is detected that uses a different pattern to visa for example.

Currently MaskedInput doesn't use setPattern to update the pattern when it changes so changing the pattern dynamically results in no changes.

deprecation error due to React.createClass

React.createClass is being deprecated in React 16.0 and currently shows deprecation warnings in 15.5

Warning: MaskedInput: React.createClass is deprecated and will be removed in version 16. Use plain JavaScript classes instead. If you're not yet ready to migrate, create-react-class is available on npm as a drop-in replacement.

Code needs to be refactored to use class MaskedInput extends Component syntax.

Can't Enter more than one character in Edge Browser

I've been getting an issue with the latest update (3.30 over 3.2.4) in the Edge Browser.

For all masked inputs on my site I can now only enter one character.

Ex. for a mask like: "111-111-111"

Once I enter "2__--" the field stops accepting character entry. I can delete or replace the first character I enter but I can't seem to type anymore. Noticing it for A and 1 masked characters.

Thanks.

autofocus attribute not set

I try to force the input to take focus when its displayed like this: <MaskedInput autoFocus={true}/> but the control does not set the attribute.

Consider Making "Mask" Not Required

In my use case, I have a very generic component where I want to have mask on maybe 20% of all components, but I do not want to have to if/then between MaskedInput and plain input. Why must "mask" be a required prop? Is this intentional?

Support for special characters

Hi, I'm trying to use the formatCharacters feature to transform special characters. Specifically japanese numbers (e.g., ๏ผ‘, ๏ผ’, etc.) to the right alpha numbers.

I tried configuring it through formatCharacters but the transform function seems to never trigger. I did some debugging and tracked the problem to this line https://github.com/insin/react-maskedinput/blob/master/src/index.js#L72 which basically will have e.target.value set to 1๏ผ’/__ but this.mask.getValue() overwrites it to 1_/__.

Please let me know if I'm missing something or if there's another way to do this.

Thanks

Input type number

When the input type is number it breaks with the following error:

Failed to read the 'selectionStart' property from 'HTMLInputElement': The input element's type ('number') does not support selection

This scenario is needed for a mobile website to bring number keyboard.

please release a newer version

Most significantly, the placeholderChar is not supported in the 2.0 release, but support has since been added. Can you publish a new version?

Cannot select date on iOS where input type="date"

in the _onChange method, where it tries to get this._getDisplayValue() on iOS with default date selector, it returns empty string and hence the date is not set. I worked around it by overriding the _onChange method for mobile view and setting the value props from the e.target.value, but thats no always gonna work.

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.