React-React maskedinput v4.0.1: Masked React component

icon
Latest Release: v4.0.1

4.0.1 / 2018-01-26 🇦🇺

  • Fix auto-fill scenarios by using data from onChange events [#112]

  • Fix wrong scope in onPaste event [#108]

  • Include React 16 in peerDependencies [#115]

  • Update nwb to 0.21.x to fix UMD build, which was exporting an object with a default property

Source code(tar.gz)
Source code(zip)

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.

Live Demo

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

Comments

  • Hide separator characters or format Monay
    Hide separator characters or format Monay

    Sep 18, 2018

    Hi, I'm trying to make inputmask to format numbers like 99,999.99 (money) and to limit it to one billion, I added size parameter and also mask=111,111,111.11 and placeholderCharacter=' ' however what I see now is , , . is there a way to hide them and show as you type?

    Reply
  • Add render prop
    Add render prop

    Jan 3, 2019

    Add a render prop so custom input components can be used

    Reply
  • This repository is dead?
    This repository is dead?

    Apr 24, 2019

    no comments for now.. so, waiting :(

    Reply
  • replace all characters with asterisk
    replace all characters with asterisk

    Apr 30, 2019

    is it possible to change all input characters to asterisk special character?

    Reply
  • space remaining inside my MaskedInput despite margin=0, padding=0 and width=auto
    space remaining inside my MaskedInput despite margin=0, padding=0 and width=auto

    Mar 27, 2020

    here the demo https://stackblitz.com/edit/react-gunzft?file=index.js.

    Why MaskedInput want to put some space at the end of the element? With standard's input the width fit to the content in this configuration.

    Here m ReactJS snippet:

    <MaskedInput 
    					class="date"
    					mask="11-11-1111" 
    					name="date" 
    					size="10" 
              value={this.state.date}
    					placeholder="dd-mm-yyyy" 
    					onChange={this.handleChange}
            />
    

    here my CSS' snippet:

    .date{
    	height:4.5vh;
    	text-align:left;
    	font-size:1.05em;
    	width:auto;
    		margin:0;
    		padding:0;
    }
    

    How can I use MaskedInput so it fit my content?

    Reply
  • When addind masked-input to my application, the scrollTo() functions bugg.
    When addind masked-input to my application, the scrollTo() functions bugg.

    Apr 19, 2020

    When addind masked-input to my application, the scrollTo() functions bugg. Browser: Mozilla Firefox 68.7.0esr on Linux Debian 10 Buster.

    Here the repository that reproduce my case: https://github.com/Hocoh/masked-input-is-makes-scrollTo-function-buggs

    You will see that when masked-input is on the page to scroll at the page's top while rendering the next step cause bugg to occurs on the scrollTo's function.

    Possibly other scroll API's functions bugg also.

    Here a react snippet of the implementation:

    `goNextStep=()=>{ let updateCurrentStep;

    	let {currentStep}=this.state; 
    	currentStep = currentStep >= 1? 1: currentStep+1;
    	
    
    	//setTimeout(()=>{
    		this.setState(currentState=>{
    			console.log("currentState.currentStep: ", currentState.currentStep)
    			updateCurrentStep=currentState.currentStep;
    			console.log("before modification => updateCurrentStep: ",updateCurrentStep)
    			updateCurrentStep= updateCurrentStep >= 2? 2: updateCurrentStep+=1;
    			console.log("after modification => updateCurrentStep: ",updateCurrentStep)
    			return({
    					currentStep:updateCurrentStep,
    					isInputFocus:false
    			})
    			}, this.FormRef.current.scrollTo(0,0)
    		)
    	// },10)
    		
    }
    
    goToPrecedingStep=()=>{
    	let currentStep=this.state.currentStep;
    	currentStep=currentStep<=0?0:currentStep-1;
    	this.setState({
    			currentStep,
    			isInputFocus:false
    		},
    		() => this.FormRef.current.scrollTo(0,0)
    	)
    }
    
    render() { 
    
    	let {
    		FormRef
    	}=this
    
    	let {
    		currentStep
    	}=this.state
    
    
    	let previousButton=() =>{
    		let{currentStep}=this.state
    		return (
    			<button 
    				className={style["form__go-to-preceding-step-button"]}
    				// className={style["form__go-to-preceding-step-button"]}
    				type="button"
    				onClick={this.goToPrecedingStep}
    			>
    				Previous step
    			</button>
    		)
    	}			
    	let nextButton =() => {
    		let{currentStep}=this.state
    		return(
    			<button
    				className={style["form__prepare-go-to-next-step-button"]}
    				type="button"
    				onClick={this.goNextStep}
    			>
    				Next step
    			</button>
    		)
    	}
    
    
    	return (
    		<div ref={FormRef}  className={style["mobile-form"]} >				
    			
    			<form onSubmit={this.handleSubmit} className={style["caterer-call-to-action-form"]} >
    			<div className={style["form__function-container"]}>
    				<p className={style["form__step-number"]} >Step {currentStep +1}/3</p>
    			</div>
    				<FirstStep
    					currentStep={currentStep}
    				/>
    				<SecondStep
    					currentStep={currentStep}
    				/>
    				<ThirdStep
    					currentStep={currentStep}
    				/>
    
    				<div className={style["form__step-button-container"]}	>
    					{ 
    						currentStep>0 &&
    						previousButton()
    					}
    					{ 
    						currentStep<4&&
    						nextButton()
    					}
    				</div>
    			</form>
    			
    		</div>
    	);
    }
    

    }

    const FirstStep= (props)=>{ if(props.currentStep!==0) return null

    return ( 
    	<div className={style["form__introduction_sequence"]}>
    		<div className={style["content"]}/>
    		
    		<MaskedInput 
    			mask="11-11-1111" 
    		/>	
    	</div>
    )
    

    }

    const SecondStep=(props)=>{ if(props.currentStep!==1) return null return <div className={style["content"]}/> }

    const ThirdStep=(props)=>{ if(props.currentStep!==2) return null return <div className={style["content"]}/> } `

    Reply
  • Warning with componentWillMount, componentWillReceiveProps and componentWillUpdate
    Warning with componentWillMount, componentWillReceiveProps and componentWillUpdate

    Oct 16, 2020

    Hi there, I am using React 16.14 and I am getting some warnings warning in the console using the MaskInput component. Warnings:

    • Warning: componentWillMount has been renamed, and is not recommended for use.
    • Warning: componentWillReceiveProps has been renamed, and is not recommended for use.
    • Warning: componentWillUpdate has been renamed, and is not recommended for use.

    This is the all the info:

    • Move data fetching code or side effects to componentDidUpdate.
    • If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state
    • Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run npx react-codemod rename-unsafe-lifecycles in your project source folder.

    Please update the following components: MaskedInput

    Does this is already solved?

    Reply
  • Please release a new version that doesn't have componentWillUpdate warnings
    Please release a new version that doesn't have componentWillUpdate warnings

    Dec 30, 2020

    I see that you have made the changes, but didn't release a new version. Can you please release a new version.

    Reply
  • Working with Microsoft IME keyboard
    Working with Microsoft IME keyboard

    Apr 29, 2021

    My customer is Japanese, he wants can typing with an IME keyboard on this mask. But I can't find any solution for that. Can you support the IME keyboard?

    Reply
  • Skipping static content while typing on mobile (chrome , opera and ..)
    Skipping static content while typing on mobile (chrome , opera and ..)

    Oct 7, 2021

    Consider I have a mask with value 111---111. In desktop browser everything is ok and --- static content is skipped while typing, But this skipping doesn't work on mobile browsers.

    Reply
  • Use class instead React.createClass
    Use class instead React.createClass

    Apr 14, 2017

    Use class instead React.createClass and use prop-types package instead React.PropTypes to prevent deprecation warning fix #70 fix #93

    Reply
  • deprecation error due to React.createClass
    deprecation error due to React.createClass

    Apr 10, 2017

    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.

    Reply
  • Pattern changes are not immediately reflected
    Pattern changes are not immediately reflected

    May 15, 2015

    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.

    bug 
    Reply
  • Use React v16
    Use React v16

    Oct 6, 2017

    React v16 is released recently and it would be great if react-maskedinput uses latest version of React.

    Reply
  • #BugFix: Issue #19
    #BugFix: Issue #19

    Apr 20, 2016

    Doesn’t work in Google Chrome for Android

    Reply
  • Browser Bundles links not working
    Browser Bundles links not working

    Mar 9, 2016

    These links aren't working:

    README.md point to them at the Browser Bundle section

    Reply
  • Can't Enter more than one character in Edge Browser
    Can't Enter more than one character in Edge Browser

    Nov 9, 2016

    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.

    Reply
  • Doesn't work in Google Chrome for Android
    Doesn't work in Google Chrome for Android

    Oct 13, 2015

    As far as I see this is because Android doesn't generate onKeyPress event for inputs...

    Reply
  • Incompatibility with react 15.4.0
    Incompatibility with react 15.4.0

    Nov 16, 2016

    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 👍

    Reply
  • Added fixes from the PR board.
    Added fixes from the PR board.

    May 20, 2016

    Add support for updating the mask. Fixes #8.

    Previously the cursor would go to the end of the input if you changed the mask or re-created the MaskedInput field. So, if you have a user typing 34 and then switching the mask to 1111 111111 11111 the cursor would be positioned to the end: 34__ ______ _____^.

    This PR takes suggestions from PR #9.

    Reply