Gerald Wichmann
Gerald Wichmann

Reputation: 457

How do I format AntD form input fields such as phone numbers and SSNs in React?

I have an AntD form with an Input field for phone numbers, and another to capture SSN's. As a user types a phone number or SSN, I would like the fields to format accordingly.

For example, instead of the phone number being 1234567890 as typed into the field, it should format as (123) 456-7890 with it initially being (___) ___-____. Similarly, in the SSN field if a user types their SSN such as 123456789 it should format as 123-45-6789 with it initially being ###-##-####.

What I'm really looking for is the proper way to do this in AntD. So not necessarily fixing the approach I'm trying to get to work.

I've been trying a variety of approaches to solve this, but none ever seem to work for me. For example, I've tried:

  1. Use onChange and create a normalizeInput function as outlined here.
  2. After thinking to myself that I shouldn't need to reinvent the wheel and there must be an npm package that I can simply leverage, I tried installing and using react-number-format. It was formatting the field and contents the way that I wanted but I lost the AntD UI (the input field no longer looked like an AntD input field).
  3. Tried playing with a Form's getFieldsValue and setFieldsValue tags but got nowhere fast. I probably just didn't know what I was doing.
  4. Tried using AntD's InputNumber function instead once i saw it had a formatter field that'd do the trick. But I abandoned that approach given I didn't want the up and down arrow controls that come with an InputNumber widget.

Currently #1 sort of works but not quite and I'm not sure why. It uses onChange to read in the current value, and adjust it accordingly, but there are two problems..

  1. previousValue becomes undefined on the 6th, 8th, and 10th digit. Why? You'll see it in console.log in my codesandbox below.
  2. The UI's field never sets using the value tag. Why? I can see the value is changing via console.log, but would've thought the setState function would've set the state within onChange, and therefore the field would show the formatted version due to the value tag..?

Here is my codesandbox illustrating the problem (MyForm.js file).

Upvotes: 1

Views: 12719

Answers (1)

Black Hole
Black Hole

Reputation: 1382

check this https://github.com/antoniopresto/antd-mask-input

is a library to make it. The component is

<MaskedInput mask="11/1111" name="expiry" placeholder="mm/yyyy" onChange={this._onChange}/>

where you give the prop "mask", where you can make the format.

in your case it would be

<MaskedInput mask="(111) 111-1111" name="expiry" placeholder="mm/yyyy" onChange={this._onChange}/>

Upvotes: 4

Related Questions