0
# Pattern Formatting
1
2
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.
3
4
## Capabilities
5
6
### PatternFormat Component
7
8
React component that formats input according to a specified pattern, with masking support for clear visual guidance to users.
9
10
```typescript { .api }
11
/**
12
* PatternFormat component for custom string pattern formatting
13
* @param props - Configuration options for pattern formatting
14
* @returns React element with pattern-formatted input
15
*/
16
function PatternFormat<BaseType = InputAttributes>(
17
props: PatternFormatProps<BaseType>
18
): React.ReactElement;
19
20
interface PatternFormatProps<BaseType = InputAttributes> {
21
/** The format pattern string using # for user input positions */
22
format: string;
23
/** Character(s) to show in unfilled positions. Can be string or array for position-specific masks */
24
mask?: string | string[];
25
/** Whether to show the full pattern even when input is empty */
26
allowEmptyFormatting?: boolean;
27
/** Character representing user input positions in the format string. Default is '#' */
28
patternChar?: string;
29
}
30
```
31
32
**Usage Examples:**
33
34
```typescript
35
import React from "react";
36
import { PatternFormat } from "react-number-format";
37
38
// Phone number formatting
39
function PhoneInput({ value, onChange }) {
40
return (
41
<PatternFormat
42
format="(###) ###-####"
43
allowEmptyFormatting
44
mask="_"
45
value={value}
46
onValueChange={(values) => onChange(values.value)}
47
placeholder="(___) ___-____"
48
/>
49
);
50
}
51
52
// Credit card formatting
53
function CreditCardInput({ value, onChange }) {
54
return (
55
<PatternFormat
56
format="#### #### #### ####"
57
mask="_"
58
value={value}
59
onValueChange={(values) => onChange(values.value)}
60
placeholder="____ ____ ____ ____"
61
/>
62
);
63
}
64
65
// Date formatting (MM/DD/YYYY)
66
function DateInput({ value, onChange }) {
67
return (
68
<PatternFormat
69
format="##/##/####"
70
mask={['M', 'M', 'D', 'D', 'Y', 'Y', 'Y', 'Y']}
71
value={value}
72
onValueChange={(values) => onChange(values.value)}
73
placeholder="MM/DD/YYYY"
74
/>
75
);
76
}
77
78
// Social Security Number
79
function SSNInput({ value, onChange }) {
80
return (
81
<PatternFormat
82
format="###-##-####"
83
mask="_"
84
value={value}
85
onValueChange={(values) => onChange(values.value)}
86
placeholder="___-__-____"
87
/>
88
);
89
}
90
91
// Custom pattern with validation
92
function ProductCodeInput({ value, onChange }) {
93
return (
94
<PatternFormat
95
format="ABC-####-XYZ"
96
patternChar="#"
97
allowEmptyFormatting
98
value={value}
99
onValueChange={(values) => onChange(values.value)}
100
isAllowed={(values) => {
101
// Only allow if all positions are filled or empty
102
const { value } = values;
103
return value.length === 0 || value.length === 7;
104
}}
105
/>
106
);
107
}
108
```
109
110
### Pattern Formatter Function
111
112
Standalone formatting function for applying pattern formatting to strings without React components.
113
114
```typescript { .api }
115
/**
116
* Format a string according to a specified pattern
117
* @param numStr - The input string to format
118
* @param props - Pattern formatting configuration
119
* @returns Formatted string with pattern applied
120
*/
121
function patternFormatter<BaseType = InputAttributes>(
122
numStr: string,
123
props: PatternFormatProps<BaseType>
124
): string;
125
```
126
127
**Usage Examples:**
128
129
```typescript
130
import { patternFormatter } from "react-number-format";
131
132
// Format phone numbers on server or in utilities
133
const formatPhoneNumber = (phone: string) => {
134
return patternFormatter(phone.replace(/\D/g, ''), {
135
format: "(###) ###-####",
136
mask: "_"
137
});
138
};
139
140
console.log(formatPhoneNumber("1234567890")); // "(123) 456-7890"
141
142
// Format credit card numbers
143
const formatCreditCard = (cardNumber: string) => {
144
return patternFormatter(cardNumber.replace(/\D/g, ''), {
145
format: "#### #### #### ####",
146
mask: "_"
147
});
148
};
149
150
console.log(formatCreditCard("1234567890123456")); // "1234 5678 9012 3456"
151
152
// Format with custom pattern character
153
const formatProductCode = (code: string) => {
154
return patternFormatter(code, {
155
format: "PRD-@@@@-END",
156
patternChar: "@"
157
});
158
};
159
160
console.log(formatProductCode("ABCD")); // "PRD-ABCD-END"
161
```
162
163
### Remove Pattern Formatting
164
165
Function to extract the raw input value from pattern-formatted strings, removing all formatting characters and patterns.
166
167
```typescript { .api }
168
/**
169
* Remove pattern formatting from a string to get raw input value
170
* @param value - The formatted string to parse
171
* @param changeMeta - Metadata about the change (for cursor positioning)
172
* @param props - The pattern formatting configuration that was applied
173
* @returns Raw input string without pattern formatting
174
*/
175
function removePatternFormat<BaseType = InputAttributes>(
176
value: string,
177
changeMeta: ChangeMeta,
178
props: PatternFormatProps<BaseType>
179
): string;
180
```
181
182
**Usage Examples:**
183
184
```typescript
185
import { removePatternFormat } from "react-number-format";
186
187
// Parse phone numbers
188
const parsePhoneNumber = (formattedPhone: string) => {
189
return removePatternFormat(formattedPhone, undefined, {
190
format: "(###) ###-####",
191
patternChar: "#"
192
});
193
};
194
195
console.log(parsePhoneNumber("(123) 456-7890")); // "1234567890"
196
197
// Parse credit card numbers
198
const parseCreditCard = (formattedCard: string) => {
199
return removePatternFormat(formattedCard, undefined, {
200
format: "#### #### #### ####",
201
patternChar: "#"
202
});
203
};
204
205
console.log(parseCreditCard("1234 5678 9012 3456")); // "1234567890123456"
206
207
// Parse dates
208
const parseDate = (formattedDate: string) => {
209
return removePatternFormat(formattedDate, undefined, {
210
format: "##/##/####",
211
patternChar: "#"
212
});
213
};
214
215
console.log(parseDate("12/25/2023")); // "12252023"
216
```
217
218
### Get Pattern Caret Boundary
219
220
Function that determines valid caret positions within pattern-formatted strings, ensuring the cursor can only be placed at input positions (not on formatting characters).
221
222
```typescript { .api }
223
/**
224
* Get array of valid caret positions for pattern-formatted value
225
* @param formattedValue - The formatted pattern string
226
* @param props - The pattern formatting configuration
227
* @returns Array of booleans indicating valid caret positions
228
*/
229
function getPatternCaretBoundary<BaseType = InputAttributes>(
230
formattedValue: string,
231
props: PatternFormatProps<BaseType>
232
): boolean[];
233
```
234
235
### Use Pattern Format Hook
236
237
React hook that converts PatternFormat props into NumberFormatBase props, useful for building custom components that need pattern formatting behavior.
238
239
```typescript { .api }
240
/**
241
* Hook that provides pattern formatting logic for custom components
242
* @param props - PatternFormat configuration
243
* @returns Props ready for NumberFormatBase component
244
*/
245
function usePatternFormat<BaseType = InputAttributes>(
246
props: PatternFormatProps<BaseType>
247
): NumberFormatBaseProps<BaseType>;
248
```
249
250
**Usage Examples:**
251
252
```typescript
253
import React from "react";
254
import { usePatternFormat, NumberFormatBase } from "react-number-format";
255
256
// Custom phone input with additional validation
257
function CustomPhoneInput({ value, onChange, onValidation }) {
258
const patternFormatProps = usePatternFormat({
259
format: "(###) ###-####",
260
mask: "_",
261
value,
262
onValueChange: (values) => {
263
onChange(values.value);
264
// Validate phone number completeness
265
const isComplete = values.value.length === 10;
266
onValidation(isComplete);
267
},
268
});
269
270
return (
271
<div className="phone-input-wrapper">
272
<NumberFormatBase
273
{...patternFormatProps}
274
customInput={(props) => (
275
<input
276
{...props}
277
className={`phone-input ${props.value?.length === 14 ? 'complete' : ''}`}
278
/>
279
)}
280
/>
281
</div>
282
);
283
}
284
```
285
286
## Common Pattern Examples
287
288
### Phone Number Patterns
289
290
```typescript
291
// US phone number
292
format="(###) ###-####" // (123) 456-7890
293
294
// International with country code
295
format="+1 (###) ###-####" // +1 (123) 456-7890
296
297
// Simple dashed format
298
format="###-###-####" // 123-456-7890
299
300
// Dotted format
301
format="###.###.####" // 123.456.7890
302
```
303
304
### Credit Card Patterns
305
306
```typescript
307
// Standard 16-digit card
308
format="#### #### #### ####" // 1234 5678 9012 3456
309
310
// American Express (15 digits)
311
format="#### ###### #####" // 1234 567890 12345
312
313
// Diners Club (14 digits)
314
format="#### ###### ####" // 1234 567890 1234
315
```
316
317
### Date and Time Patterns
318
319
```typescript
320
// US date format
321
format="##/##/####" // 12/25/2023
322
323
// European date format
324
format="##.##.####" // 25.12.2023
325
326
// ISO date format
327
format="####-##-##" // 2023-12-25
328
329
// Time format
330
format="##:##:##" // 14:30:25
331
332
// Date and time
333
format="##/##/#### ##:##" // 12/25/2023 14:30
334
```
335
336
### ID and Code Patterns
337
338
```typescript
339
// Social Security Number
340
format="###-##-####" // 123-45-6789
341
342
// ZIP Code
343
format="#####" // 12345
344
format="#####-####" // 12345-6789
345
346
// Product codes
347
format="ABC-###-XYZ" // ABC-123-XYZ
348
349
// License plates
350
format="### ###" // ABC 123
351
```
352
353
## Advanced Masking
354
355
### Position-Specific Masks
356
357
Use arrays to provide different mask characters for different positions:
358
359
```typescript
360
<PatternFormat
361
format="##/##/####"
362
mask={['M', 'M', 'D', 'D', 'Y', 'Y', 'Y', 'Y']}
363
allowEmptyFormatting
364
/> // Shows: MM/DD/YYYY when empty
365
```
366
367
### Conditional Formatting
368
369
```typescript
370
// Dynamic pattern based on input length
371
function DynamicCardInput({ value, onChange }) {
372
// Determine card type and pattern based on first digits
373
const getPattern = (value: string) => {
374
if (value.startsWith('34') || value.startsWith('37')) {
375
return "#### ###### #####"; // Amex
376
}
377
return "#### #### #### ####"; // Standard
378
};
379
380
return (
381
<PatternFormat
382
format={getPattern(value || '')}
383
mask="_"
384
value={value}
385
onValueChange={(values) => onChange(values.value)}
386
/>
387
);
388
}
389
```