sanniassin / react-input-mask

Input masking component for React. Made with attention to UX.
MIT License
2.24k stars 255 forks source link

Optional character #20

Open cezarsmpio opened 8 years ago

cezarsmpio commented 8 years ago

There is a way to use a optional char?

Example: <MaskInput mask="(99) 9999-9999[9]" /> or <MaskInput mask="(99) 9999-9999{9}" /> or <MaskInput mask="(99) 9999-99999?" />

Thanks!

sanniassin commented 8 years ago

Don't understand. How should optional char act?

cezarsmpio commented 8 years ago

For example, in Brazil, some states have the phone number with one digit more. While some have 8 digits, others have 9 digits.

cezarsmpio commented 8 years ago

Hi @sanniassin, any progress?

Thanks! :)

sanniassin commented 8 years ago

@CezarLuiz0 Pretty busy right now, so this project temporarily abandoned :)

cezarsmpio commented 8 years ago

Can I fork this project and send pull requests with new features?

Thanks!

sanniassin commented 8 years ago

Sure, but i will not be able to review and test PR for a while.

deser commented 8 years ago

Hi guys! Is there any progress on this feature?

dapi commented 8 years ago

I can do it for 100$ )

deser commented 8 years ago

Ok, please do it then)

dapi commented 8 years ago

Have done. Just use this configuration:

<Input 
  mask="(99) 9999-99999?"
  formatChars={
    "9": "[0-9]",
    "?": "[0-9]"
  }
 />
deser commented 8 years ago

Thank you!)

eliseumds commented 8 years ago

Guys, is this issue solved?

cezarsmpio commented 8 years ago

Not yet :/

dapi commented 8 years ago

Does not last solution fit?

leaopedro commented 8 years ago

Hey guys, how is this issue?

mquandalle commented 8 years ago

Does anyone has a solution to have a formatted input for currencies, like USD 1,000?

deser commented 8 years ago

There is Intl standard. You can use react Intl as well

mquandalle commented 8 years ago

Sure, but the difficult part is to have an <input> that auto-format the number as the user types it. Like autoNumeric in the jQuery world.

sashashakun commented 8 years ago

@mquandalle I use http://numeraljs.com/ for this solving this task

alymenbr commented 7 years ago

Hi guys,

I had the same problem with the different formatted phone numbers. I solved using a mask like this:

<InputElement
    mask="(99) 9999tt999?" 
    formatChars={{"9": "[0-9]", "t": "[0-9\-]", "?": "[0-9 ]"}} 
    maskChar={null} />

Now both formats are accepted. As there is no placeholder character, it looks fine for the user.

kaueburiti commented 7 years ago

Great solution, @alymenbr! But i don't think that the issue is solved, because all this solutions are just "work arounds" for a feature that does no exists.

dkouk commented 6 years ago

Hi guys, I have a issue with creating mask for zipcode US, as some 5 digits, and some have 9 digits, I try to make a "work around" like this : mask="99999?????" formatChars={{ 9: '[0-9]', '?': '[-\0-9]' }} but not working correctly, is there any suggestion ?

andredovale commented 6 years ago

For controlled inputs:

handlerChangeBrazilianPhone = (ev) => {
  const brazilianPhone = ev.target.value.replace(/[^0-9]+/g, '')
  this.setState({ brazilianPhone })
}
...
mask={this.state.brazilianPhone.length <= 10 ? '(99) 9999-9999?' : '(99) 99999-9999'}
formatChars={{ 9: '[0-9]', '?': '[0-9 ]' }}
onChange={this.handlerChangeBrazilianPhone}
value={this.state.brazilianPhone}
sanniassin commented 6 years ago

@dkouk Could you take a look at the master branch? It has new beforeChange property and example with your case.

nagapriyanka93 commented 6 years ago

is there a way to achieve this inputmask("9{2,3}/9{2,3}").inputmask("option", {tabThrough: true}) using input mask in react? I am looking to use a mask where i can enter 2 or 3 numbers before / if i enter 2 numbers ( e.g 12_/___)and press tab it should take me to the second portion after /.

Any help is highly appreciated.

Abhishek-Palapi commented 6 years ago

hi i want react mask for values 1 to 100 i am using "99%" mask but its not taking the 100 value i want to include the 100 max value also

fiuzagr commented 5 years ago
import React, { useState } from 'react';
import InputMask from 'react-input-mask';
import { trim, size } from 'lodash';

const PhoneInput = ({ className, ...props }) => {
  const [mask, setMask] = useState('(99) 99999-9999');

  return (
    <InputMask
      {...props}
      mask={mask}
      onBlur={e => {
        if (size(trim(e.target.value, '_')) === 14) {
          setMask('(99) 9999-9999');
        }
      }}
      onFocus={e => {
        if (size(trim(e.target.value, '_')) === 14) {
          setMask('(99) 99999-9999');
        }
      }}
    >
      {inputProps => (<input {...inputProps} type="tel" />)}
    </InputMask>
  );
};
cescoferraro commented 4 years ago

to whoever falls here searching for an react-number-format solution

          const s = values.phone
            .split(" ")
            .join("")
            .split(")")
            .join("")
            .split("(")
            .join("")
            .split("-")
            .join("")
            .split("_")
            .join("")

format={s.length < 11 ? "(##) ####-#####" : "(##) #####-####"}
mask={s.length < 10 ? "_" : ""}
hugosbg commented 4 years ago

I did like this

with: react-input-mask: ^2.0.4

import React from "react";
import InputMask, { InputState } from "react-input-mask";
import { TextField } from "@material-ui/core";

function PhoneMask() {
  const beforeMaskedValueChange = (newState: InputState) => {
    let { value } = newState;

    const newValue = value.replace(/\D/g, "");
    if (newValue.length === 11) {
      value = newValue.replace(/^(\d{2})(\d{5})(\d{4})$/, "($1) $2-$3");
    }

    return {
      ...newState,
      value
    };
  };

  return (
    <InputMask mask="(99) 9999-99999" maskChar={null} beforeMaskedValueChange={beforeMaskedValueChange}>
      {(props: any) => <TextField {...props} fullWidth label="Phone" name="phone" />}
    </InputMask>
  );
};
marlosirapuan commented 4 years ago

perfect, @hugosbg 👌 thank you.

optimus-informatica commented 4 years ago

const phoneMask = '+55 (99) 9999-9999'; const celphoneMask = '+55 (99) 99999-9999'; const [mask, setMask] = useState(phoneMask);

const changeMask = (e) => { if (/^\+([0-9]+) \(([0-9]+)\) 9/.test(e.target.value)) { if (mask !== celphoneMask) { setMask(celphoneMask); } } else if (mask != phoneMask) { setMask(phoneMask); } } <ImputMask mask={mask} maskChar="_" onChange={changeMask}>

bianchi commented 3 years ago

I made it work on version 3, alpha 2. I'm using material UI and typescript. For anyone interested.

https://codesandbox.io/s/confident-bird-fek84?fontsize=14&hidenavigation=1&theme=dark

jvmendesavila commented 3 years ago

No meu caso funcionou da seguinte maneira:

mask={ formik.values.phone.length > 14 ? '(99) 99999-9999' : '(99) 9999-99999' }

espero que ajude 🙏

alanddos commented 3 years ago

Deu certo assim aqui <TextField error={touched.number && Boolean(errors.number)} helperText={touched.number && errors.number} label={i18n.t("contactModal.form.number")} name="number" variant="outlined" margin="dense" onKeyUp={e => { if (e.target.value.replace(/\D/g, "").length === 10) { let x = e.target.value.replace(/\D/g, "").match(/(\d{0,2})(\d{0,4})(\d{0,4})/); e.target.value = !x[2] ? x[1] : "(" + x[1] + ") " + x[2] + (x[3] ? "-" + x[3] : ""); } else { let x = e.target.value.replace(/\D/g, "").match(/(\d{0,2})(\d{0,1})(\d{0,4})(\d{0,4})/); e.target.value = !x[2] ? x[1] : "(" + x[1] + ") " + x[2] + " " + x[3] + (x[4] ? "-" + x[4] : ""); } }} />

fernandogatto commented 3 years ago

Hi guys, I used InputMask from react-input-mask and TextField from @material-ui/core and it works that way:

const [inputTextData, setInputTextData] = useState({
    celular: '',
});`
const handleInputTextChange = (event) => {
    const { name, value } = event.target;

    setInputTextData({...inputTextData, [name]: value});
} 
<InputMask
    mask={inputTextData.celular.length > 14 ? "(99) 99999-9999" : "(99) 9999-99999"}
    maskChar=""
    value={inputTextData.celular}
    onChange={handleInputTextChange}
>
    {() => (
        <TextField
            variant="outlined"
            type="tel"
            label="Celular"
            name="celular"
        />
      )}
</InputMask> 

Attention to the second condition on prop mask. It must be have 15 characters to can pass to the first condition.

eeebuba commented 2 years ago

mask={watch('phone')!.charAt(5) === '9' ? '(99) 9 9999-9999' : '(99) 9999-9999'} doesn't this work too? (using with react-hook-form)

leoburn5 commented 2 years ago

Have done. Just use this configuration:

<Input 
  mask="(99) 9999-99999?"
  formatChars={
    "9": "[0-9]",
    "?": "[0-9]"
  }
 />

This solution does not solve the issue.

Unfortunately the presented mask is not correct, because is the first digit after the area code that should be optional.

Also, the five digit sequence is bad for reading.

A good solution would be using for instance "9" for mandatory positions and "0" for optional positions or vice versa like this:

(99) 0 9999-9999, with the empty mask like this (__) _ ____-____

The spaces around the optional digit should make the value easyer to read.

This package seems to be dead, will search for other options