React component library for formatting numbers in input fields and text display with sophisticated caret engine and customizable patterns.
—
Custom string pattern formatting with input masking for phone numbers, credit cards, dates, social security numbers, and any structured text format. Provides visual formatting while users type and ensures data consistency.
React component that formats input according to a specified pattern, with masking support for clear visual guidance to users.
/**
* PatternFormat component for custom string pattern formatting
* @param props - Configuration options for pattern formatting
* @returns React element with pattern-formatted input
*/
function PatternFormat<BaseType = InputAttributes>(
props: PatternFormatProps<BaseType>
): React.ReactElement;
interface PatternFormatProps<BaseType = InputAttributes> {
/** The format pattern string using # for user input positions */
format: string;
/** Character(s) to show in unfilled positions. Can be string or array for position-specific masks */
mask?: string | string[];
/** Whether to show the full pattern even when input is empty */
allowEmptyFormatting?: boolean;
/** Character representing user input positions in the format string. Default is '#' */
patternChar?: string;
}Usage Examples:
import React from "react";
import { PatternFormat } from "react-number-format";
// Phone number formatting
function PhoneInput({ value, onChange }) {
return (
<PatternFormat
format="(###) ###-####"
allowEmptyFormatting
mask="_"
value={value}
onValueChange={(values) => onChange(values.value)}
placeholder="(___) ___-____"
/>
);
}
// Credit card formatting
function CreditCardInput({ value, onChange }) {
return (
<PatternFormat
format="#### #### #### ####"
mask="_"
value={value}
onValueChange={(values) => onChange(values.value)}
placeholder="____ ____ ____ ____"
/>
);
}
// Date formatting (MM/DD/YYYY)
function DateInput({ value, onChange }) {
return (
<PatternFormat
format="##/##/####"
mask={['M', 'M', 'D', 'D', 'Y', 'Y', 'Y', 'Y']}
value={value}
onValueChange={(values) => onChange(values.value)}
placeholder="MM/DD/YYYY"
/>
);
}
// Social Security Number
function SSNInput({ value, onChange }) {
return (
<PatternFormat
format="###-##-####"
mask="_"
value={value}
onValueChange={(values) => onChange(values.value)}
placeholder="___-__-____"
/>
);
}
// Custom pattern with validation
function ProductCodeInput({ value, onChange }) {
return (
<PatternFormat
format="ABC-####-XYZ"
patternChar="#"
allowEmptyFormatting
value={value}
onValueChange={(values) => onChange(values.value)}
isAllowed={(values) => {
// Only allow if all positions are filled or empty
const { value } = values;
return value.length === 0 || value.length === 7;
}}
/>
);
}Standalone formatting function for applying pattern formatting to strings without React components.
/**
* Format a string according to a specified pattern
* @param numStr - The input string to format
* @param props - Pattern formatting configuration
* @returns Formatted string with pattern applied
*/
function patternFormatter<BaseType = InputAttributes>(
numStr: string,
props: PatternFormatProps<BaseType>
): string;Usage Examples:
import { patternFormatter } from "react-number-format";
// Format phone numbers on server or in utilities
const formatPhoneNumber = (phone: string) => {
return patternFormatter(phone.replace(/\D/g, ''), {
format: "(###) ###-####",
mask: "_"
});
};
console.log(formatPhoneNumber("1234567890")); // "(123) 456-7890"
// Format credit card numbers
const formatCreditCard = (cardNumber: string) => {
return patternFormatter(cardNumber.replace(/\D/g, ''), {
format: "#### #### #### ####",
mask: "_"
});
};
console.log(formatCreditCard("1234567890123456")); // "1234 5678 9012 3456"
// Format with custom pattern character
const formatProductCode = (code: string) => {
return patternFormatter(code, {
format: "PRD-@@@@-END",
patternChar: "@"
});
};
console.log(formatProductCode("ABCD")); // "PRD-ABCD-END"Function to extract the raw input value from pattern-formatted strings, removing all formatting characters and patterns.
/**
* Remove pattern formatting from a string to get raw input value
* @param value - The formatted string to parse
* @param changeMeta - Metadata about the change (for cursor positioning)
* @param props - The pattern formatting configuration that was applied
* @returns Raw input string without pattern formatting
*/
function removePatternFormat<BaseType = InputAttributes>(
value: string,
changeMeta: ChangeMeta,
props: PatternFormatProps<BaseType>
): string;Usage Examples:
import { removePatternFormat } from "react-number-format";
// Parse phone numbers
const parsePhoneNumber = (formattedPhone: string) => {
return removePatternFormat(formattedPhone, undefined, {
format: "(###) ###-####",
patternChar: "#"
});
};
console.log(parsePhoneNumber("(123) 456-7890")); // "1234567890"
// Parse credit card numbers
const parseCreditCard = (formattedCard: string) => {
return removePatternFormat(formattedCard, undefined, {
format: "#### #### #### ####",
patternChar: "#"
});
};
console.log(parseCreditCard("1234 5678 9012 3456")); // "1234567890123456"
// Parse dates
const parseDate = (formattedDate: string) => {
return removePatternFormat(formattedDate, undefined, {
format: "##/##/####",
patternChar: "#"
});
};
console.log(parseDate("12/25/2023")); // "12252023"Function that determines valid caret positions within pattern-formatted strings, ensuring the cursor can only be placed at input positions (not on formatting characters).
/**
* Get array of valid caret positions for pattern-formatted value
* @param formattedValue - The formatted pattern string
* @param props - The pattern formatting configuration
* @returns Array of booleans indicating valid caret positions
*/
function getPatternCaretBoundary<BaseType = InputAttributes>(
formattedValue: string,
props: PatternFormatProps<BaseType>
): boolean[];React hook that converts PatternFormat props into NumberFormatBase props, useful for building custom components that need pattern formatting behavior.
/**
* Hook that provides pattern formatting logic for custom components
* @param props - PatternFormat configuration
* @returns Props ready for NumberFormatBase component
*/
function usePatternFormat<BaseType = InputAttributes>(
props: PatternFormatProps<BaseType>
): NumberFormatBaseProps<BaseType>;Usage Examples:
import React from "react";
import { usePatternFormat, NumberFormatBase } from "react-number-format";
// Custom phone input with additional validation
function CustomPhoneInput({ value, onChange, onValidation }) {
const patternFormatProps = usePatternFormat({
format: "(###) ###-####",
mask: "_",
value,
onValueChange: (values) => {
onChange(values.value);
// Validate phone number completeness
const isComplete = values.value.length === 10;
onValidation(isComplete);
},
});
return (
<div className="phone-input-wrapper">
<NumberFormatBase
{...patternFormatProps}
customInput={(props) => (
<input
{...props}
className={`phone-input ${props.value?.length === 14 ? 'complete' : ''}`}
/>
)}
/>
</div>
);
}// US phone number
format="(###) ###-####" // (123) 456-7890
// International with country code
format="+1 (###) ###-####" // +1 (123) 456-7890
// Simple dashed format
format="###-###-####" // 123-456-7890
// Dotted format
format="###.###.####" // 123.456.7890// Standard 16-digit card
format="#### #### #### ####" // 1234 5678 9012 3456
// American Express (15 digits)
format="#### ###### #####" // 1234 567890 12345
// Diners Club (14 digits)
format="#### ###### ####" // 1234 567890 1234// US date format
format="##/##/####" // 12/25/2023
// European date format
format="##.##.####" // 25.12.2023
// ISO date format
format="####-##-##" // 2023-12-25
// Time format
format="##:##:##" // 14:30:25
// Date and time
format="##/##/#### ##:##" // 12/25/2023 14:30// Social Security Number
format="###-##-####" // 123-45-6789
// ZIP Code
format="#####" // 12345
format="#####-####" // 12345-6789
// Product codes
format="ABC-###-XYZ" // ABC-123-XYZ
// License plates
format="### ###" // ABC 123Use arrays to provide different mask characters for different positions:
<PatternFormat
format="##/##/####"
mask={['M', 'M', 'D', 'D', 'Y', 'Y', 'Y', 'Y']}
allowEmptyFormatting
/> // Shows: MM/DD/YYYY when empty// Dynamic pattern based on input length
function DynamicCardInput({ value, onChange }) {
// Determine card type and pattern based on first digits
const getPattern = (value: string) => {
if (value.startsWith('34') || value.startsWith('37')) {
return "#### ###### #####"; // Amex
}
return "#### #### #### ####"; // Standard
};
return (
<PatternFormat
format={getPattern(value || '')}
mask="_"
value={value}
onValueChange={(values) => onChange(values.value)}
/>
);
}Install with Tessl CLI
npx tessl i tessl/npm-react-number-format