Masked inputs are used to restrict and format user input in a specific way, such as phone numbers, dates, or credit card numbers. They help ensure the input adheres to a specific pattern, reducing errors and improving the user experience.
In React, you can implement masked inputs using libraries like react-input-mask
or by manually managing the input format with state and regular expressions.
Let’s explore both approaches to handling masked inputs like phone numbers and dates in React.
1. Using react-input-mask
for Masked Inputs
react-input-mask
is a popular library that helps easily mask inputs in React, supporting patterns for phone numbers, dates, credit cards, and other types of formatted inputs.
Installation:
npm install react-input-mask
Example: Phone Number Masking with react-input-mask
import React, { useState } from 'react';
import InputMask from 'react-input-mask';
const PhoneNumberInput = () => {
const [phone, setPhone] = useState('');
const handleChange = (e) => {
setPhone(e.target.value);
};
return (
<div>
<label htmlFor="phone">Phone Number: </label>
<InputMask
mask="(999) 999-9999" // Define mask for phone number
value={phone}
onChange={handleChange}
id="phone"
placeholder="(123) 456-7890"
/>
</div>
);
};
export default PhoneNumberInput;
Explanation:
- Masking:
mask="(999) 999-9999"
defines a mask where9
represents a digit. The mask enforces a phone number format like(123) 456-7890
. - State Management: The input value is managed with React state using
useState
. InputMask
Component: This component automatically formats the input according to the specified mask.
Example: Date Input Masking
import React, { useState } from 'react';
import InputMask from 'react-input-mask';
const DateInput = () => {
const [date, setDate] = useState('');
const handleChange = (e) => {
setDate(e.target.value);
};
return (
<div>
<label htmlFor="date">Date: </label>
<InputMask
mask="99/99/9999" // Mask format for date (MM/DD/YYYY)
value={date}
onChange={handleChange}
id="date"
placeholder="MM/DD/YYYY"
/>
</div>
);
};
export default DateInput;
Explanation:
- Masking:
mask="99/99/9999"
ensures that the input follows theMM/DD/YYYY
format. - User Experience: The placeholder and mask guide the user to enter the date correctly.
2. Implementing Masked Inputs Manually
If you prefer not to use external libraries, you can implement your own masked input logic in React using useState
and regular expressions.
Example: Phone Number Masking with Custom Code
import React, { useState } from 'react';
const PhoneNumberInput = () => {
const [phone, setPhone] = useState('');
const handleChange = (e) => {
let value = e.target.value;
value = value.replace(/\D/g, ''); // Remove all non-digit characters
if (value.length <= 3) {
value = `(${value}`;
} else if (value.length <= 6) {
value = `(${value.slice(0, 3)}) ${value.slice(3, 6)}`;
} else {
value = `(${value.slice(0, 3)}) ${value.slice(3, 6)}-${value.slice(6, 10)}`;
}
setPhone(value);
};
return (
<div>
<label htmlFor="phone">Phone Number: </label>
<input
type="text"
id="phone"
value={phone}
onChange={handleChange}
placeholder="(123) 456-7890"
/>
</div>
);
};
export default PhoneNumberInput;
Explanation:
- Regular Expression: We use the
replace(/\D/g, '')
method to strip out non-digit characters. - Manual Masking: As the user types, we format the number into the phone number format
(XXX) XXX-XXXX
.
Example: Date Masking with Custom Code
import React, { useState } from 'react';
const DateInput = () => {
const [date, setDate] = useState('');
const handleChange = (e) => {
let value = e.target.value;
value = value.replace(/\D/g, ''); // Remove all non-digit characters
if (value.length <= 2) {
value = value.slice(0, 2); // Limit month to two digits
} else if (value.length <= 4) {
value = `${value.slice(0, 2)}/${value.slice(2, 4)}`; // Add slash between month and day
} else {
value = `${value.slice(0, 2)}/${value.slice(2, 4)}/${value.slice(4, 8)}`; // Add slash between day and year
}
setDate(value);
};
return (
<div>
<label htmlFor="date">Date: </label>
<input
type="text"
id="date"
value={date}
onChange={handleChange}
placeholder="MM/DD/YYYY"
/>
</div>
);
};
export default DateInput;
Explanation:
- Date Formatting: This function manually formats the date input as
MM/DD/YYYY
, inserting slashes between the month, day, and year. - Input Restriction: It limits the input to valid date characters using regular expressions and string slicing.
3. Benefits of Masked Inputs
- User Guidance: Masked inputs provide users with a clear pattern for entering data (e.g., phone numbers, dates), reducing errors.
- Real-Time Formatting: As users type, the input is automatically formatted, making the experience smoother.
- Validation: The format can be validated easily because the input adheres to a defined structure, making backend validation simpler.
4. Handling Masked Inputs with Validation
While masked inputs provide an excellent way to format data, you should also ensure the input meets validation criteria (e.g., proper phone number or date format). This can be done by leveraging JavaScript validation libraries or using custom validation logic.
Example: Phone Number Validation
const validatePhone = (phone) => {
const regex = /^\(\d{3}\) \d{3}-\d{4}$/;
return regex.test(phone);
};
const handleSubmit = (e) => {
e.preventDefault();
if (validatePhone(phone)) {
alert('Phone number is valid!');
} else {
alert('Invalid phone number format.');
}
};