diff --git a/example/src/index.js b/example/src/index.js index 17e7402c..85afb3b1 100644 --- a/example/src/index.js +++ b/example/src/index.js @@ -154,6 +154,26 @@ class App extends React.Component {

Custom Numeral: add support for custom languages

+ +
+

Format on type

+ +
+ +
+

Format phone number on type

+ +
+ +
+

Format postal code on type

+ +
+ +
+

Format date on type

+ +
); } diff --git a/src/pattern_format.tsx b/src/pattern_format.tsx index 45bccac8..8041c204 100644 --- a/src/pattern_format.tsx +++ b/src/pattern_format.tsx @@ -9,20 +9,44 @@ import { } from './utils'; import NumberFormatBase from './number_format_base'; +function _getFormattedNumberArray(format: string, patternChar: string, numStr: string, formatOnType: boolean) { + const formatArray = format.split(''); + if (!formatOnType) { + return formatArray; + } + let hashCount = 0; + // find last pattern index + const replacePatternIdx = formatArray.findIndex((char) => { + if (char === patternChar) { + hashCount += 1; + } + return hashCount === numStr.length + }) + + // filter format array until numStr length + return formatArray.filter((_, index) => { + return replacePatternIdx >= 0 + ? index <= replacePatternIdx + : true + }); +} + export function format( numStr: string, props: PatternFormatProps, ) { const format = props.format as string; - const { allowEmptyFormatting, mask, patternChar = '#' } = props; + const { allowEmptyFormatting, mask, patternChar = '#', formatOnType } = props; if (numStr === '' && !allowEmptyFormatting) return ''; - let hashCount = 0; - const formattedNumberAry = format.split(''); + const formattedNumberAry = _getFormattedNumberArray(format, patternChar, numStr, formatOnType); + + let hashCount = 0 + for (let i = 0, ln = format.length; i < ln; i++) { if (format[i] === patternChar) { - formattedNumberAry[i] = numStr[hashCount] || getMaskAtIndex(mask, hashCount); + formattedNumberAry[i] = numStr[hashCount] || getMaskAtIndex(mask, hashCount, formatOnType); hashCount += 1; } } diff --git a/src/types.ts b/src/types.ts index 93b9295f..2c0b9baf 100644 --- a/src/types.ts +++ b/src/types.ts @@ -110,6 +110,7 @@ export type PatternFormatProps = NumberFormatProps< mask?: string | string[]; allowEmptyFormatting?: boolean; patternChar?: string; + formatOnType?: boolean; }, BaseType >; diff --git a/src/utils.tsx b/src/utils.tsx index 64b158fb..0e1a63e3 100644 --- a/src/utils.tsx +++ b/src/utils.tsx @@ -294,7 +294,10 @@ export function getDefaultChangeMeta(value: string) { }; } -export function getMaskAtIndex(mask: string | string[] = ' ', index: number) { +export function getMaskAtIndex(mask: string | string[] = ' ', index: number, formatOnType = false) { + if (formatOnType) { + return ''; + } if (typeof mask === 'string') { return mask; }