React Input Mask

React Input Mask is a versatile tool for enhancing user input in React-based applications. It offers dynamic formatting and validation for various data types, such as phone numbers, 4-digit PINs, Google-style OTPs, credit card numbers, and date input.
In the phone number example, the component formats and masks phone numbers in the common "(123) 456-7890" pattern.
The 4-digit PIN example allows users to input only numeric characters and limits the length to 4 digits.
For Google-style OTPs, it provides input fields for a 6-digit code, allowing users to enter each digit separately.
The credit card example formats and masks credit card numbers, adding spaces every 4 digits.
Lastly, the date input examples support both DD-MM-YYYY and YYYY-MM-DD formats, ensuring error-free date entry.
These masks improve user experience, prevent input errors, and enhance data integrity in React applications.




Thanks for your feedback!
Your contributions will help us to improve service.
How can I implement a phone number input mask in a React application?
The React Input Mask Phone Number example demonstrates a React component that formats and masks phone numbers as users input them. It uses the useState hook to manage a phoneNumber state. The handlePhoneNumberChange function is triggered on input change, applying a format with parentheses and dashes for the first ten digits, and leaving longer numbers unchanged. The input field displays the formatted phoneNumber, limiting the length to 14 characters. This provides a user-friendly interface for entering phone numbers, automatically formatting them as per the common (123) 456-7890 pattern, enhancing the user experience for data input
React Input Mask Phone Number
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const [phoneNumber, setPhoneNumber] = useState('');
const handlePhoneNumberChange = (e) => {
const input = e.target.value;
const formattedInput = formatPhoneNumber(input);
setPhoneNumber(formattedInput);
};
const formatPhoneNumber = (input) => {
// Remove all non-digit characters from the input
const cleanedInput = input.replace(/\D/g, '');
// Apply the phone number mask
if (cleanedInput.length <= 10) {
return cleanedInput.replace(/(\d{3})(\d{0,3})(\d{0,4})/, '($1) $2-$3');
} else {
// Handle longer phone numbers (e.g., international numbers)
return cleanedInput;
}
};
return (
<div className='container'>
<h3>React Js Input Mask for Phone Number</h3>
<label className='label'>Phone Number:</label>
<input
type="text"
className='input'
value={phoneNumber}
maxLength={14}
onChange={handlePhoneNumberChange}
placeholder="(123) 456-7890"
/>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Output of React Input Mask for Phone Number
React Input Mask 4-digit PIN
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const [pin, setPin] = useState('');
const handlePinChange = (e) => {
const value = e.target.value;
const maskedValue = value.replace(/\D/g, '').slice(0, 4); // Allow only digits and limit length to 4
setPin(maskedValue);
};
return (
<div className='container'>
<h3>React Js Input Mask for 4 Digit Pin</h3>
<label className='label'>4 Digit Pin:</label>
<input
className='input'
type="text"
value={pin}
onChange={handlePinChange}
placeholder="Enter 4-digit PIN"
maxLength={4}
/>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Output of Input Mask For 4 Digit Pin
React Input Mask Google-style OTP
xxxxxxxxxx
<script type="text/babel">
const { useState, useRef } = React;
function App() {
const otpLength = 6; // You can change this to your desired OTP length
const otpInputs = Array(otpLength).fill(null);
const inputRefs = otpInputs.map(() => useRef(null));
const [otp, setOtp] = useState(new Array(otpLength).fill(''));
const handleInputChange = (e, index) => {
const value = e.target.value;
if (!/^\d*$/.test(value)) return; // Only allow numeric input
const newOtp = [...otp];
newOtp[index] = value;
setOtp(newOtp);
if (index < otpLength - 1 && value !== '') {
inputRefs[index + 1].current.focus();
}
};
const handleBackspace = (e, index) => {
if (e.key === 'Backspace' && index > 0 && otp[index] === '') {
inputRefs[index - 1].current.focus();
}
};
return (
<div className='container'>
<h3>React Input Mask Google-style OTP</h3>
<div className="otp-container">
<span>G-</span>
{otpInputs.map((_, index) => (
<input
key={index}
type="text"
maxLength="1"
value={otp[index]}
onChange={(e) => handleInputChange(e, index)}
onKeyDown={(e) => handleBackspace(e, index)}
ref={inputRefs[index]}
/>
))}
</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Output of React Input Mask Google-style OTP
React Input Mask Credit Card
xxxxxxxxxx
<script type="text/babel">
const { useState, useRef } = React;
function App() {
const [creditCardNumber, setCreditCardNumber] = useState('');
const handleCreditCardChange = (e) => {
const input = e.target.value;
const sanitizedInput = input.replace(/\D/g, ''); // Remove non-numeric characters
let maskedInput = '';
for (let i = 0; i < sanitizedInput.length; i++) {
if (i === 4 || i === 8 || i === 12) {
maskedInput += ' ';
}
maskedInput += sanitizedInput[i];
}
setCreditCardNumber(maskedInput);
};
return (
<div className='container'>
<h3>React Input Mask For Credit Card</h3>
<label htmlFor="creditCard" className="label-class">Credit Card Number</label>
<input
type="text"
id="creditCard"
value={creditCardNumber}
onChange={handleCreditCardChange}
maxLength={19} // Maximum length of a credit card number with spaces
placeholder="XXXX XXXX XXXX XXXX"
className="input-class"
/>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Output of React Input Mask for Credit Card
React Input Mask date input - DD-MM-YYYY
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const [date, setDate] = useState('');
const handleInputChange = (e) => {
let inputDate = e.target.value;
// Remove non-numeric characters from the input
inputDate = inputDate.replace(/\D/g, '');
// Format the date as DD-MM-YYYY
if (inputDate.length <= 2) {
setDate(inputDate);
} else if (inputDate.length <= 4) {
setDate(`${inputDate.slice(0, 2)}-${inputDate.slice(2)}`);
} else if (inputDate.length <= 8) {
setDate(`${inputDate.slice(0, 2)}-${inputDate.slice(2, 4)}-${inputDate.slice(4)}`);
}
};
return (
<div className='container'>
<h3>React Input Mask Date DD-MM-YYYY</h3>
<label className='label'>Enter Date:</label>
<input
className='input-class'
type="text"
placeholder="DD-MM-YYYY"
value={date}
onChange={handleInputChange}
maxLength="10"
/>
Date: {date}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Output of React Input Mask date input - DD-MM-YYYY
React Input Mask date input - YYYY-MM-DD
xxxxxxxxxx
<script type="text/babel">
const { useState, useRef } = React;
function App() {
const [date, setDate] = useState('');
const handleInputChange = (e) => {
let inputDate = e.target.value;
// Remove non-numeric characters from the input
inputDate = inputDate.replace(/\D/g, '');
// Add hyphens to format the date as YYYY-MM-DD
if (inputDate.length <= 4) {
setDate(inputDate);
} else if (inputDate.length <= 6) {
setDate(`${inputDate.slice(0, 4)}-${inputDate.slice(4)}`);
} else if (inputDate.length <= 8) {
setDate(`${inputDate.slice(0, 4)}-${inputDate.slice(4, 6)}-${inputDate.slice(6)}`);
}
};
return (
<div className='container'>
<h3>React Input Mask Date YYYY-MM-DD</h3>
<label className='label'>Enter Date:</label>
<input
type="text"
placeholder="YYYY-MM-DD"
value={date}
onChange={handleInputChange}
maxLength="10"
className='input-class'
/>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>