Skip to content

Commit

Permalink
fix: update textfield masking auto add special character logic
Browse files Browse the repository at this point in the history
affects: @medly-components/core
  • Loading branch information
gmukul01 committed Apr 28, 2024
1 parent 5d3efa9 commit 38bc390
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 13 deletions.
4 changes: 0 additions & 4 deletions packages/core/src/components/TextField/getMaskedValue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@ describe('getMaskedValue function', () => {
expect(maskedValue('11 / 11 / 11111')).toEqual('11 / 11 / 1111');
});

it('should truncate special character from end if any', () => {
expect(maskedValue('11 / 11 /')).toEqual('11 / 11');
});

it('should add special character in between', () => {
expect(maskedValue('11 / 111')).toEqual('11 / 11 / 1');
});
Expand Down
16 changes: 7 additions & 9 deletions packages/core/src/components/TextField/getMaskedValue.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const applyMasking = (value: string, mask: string): string => {
const applyMasking = (value: string, mask: string, selectionStart: number): string => {
const { length } = value,
lastChar = value.charAt(length - 1),
alphaRegex = /[a-zA-Z]/, //NOSONAR
Expand All @@ -10,13 +10,11 @@ const applyMasking = (value: string, mask: string): string => {
if (length > mask.length || alphaRegex.test(lastChar)) {
// if user types more char then mask length
newValue = value.slice(0, -1);
} else if (specialCharsRegex.test(mask.charAt(length - 1))) {
// if user reaches to special character
const remainingMask = mask.substr(length - 1),
numberIndex = remainingMask.match(alphaNumericRegex)?.index;

newValue = value.slice(0, -1) + remainingMask.substr(0, numberIndex) + value.slice(-1);
} else if (specialCharsRegex.test(mask.charAt(length))) {
} else if (
specialCharsRegex.test(mask.charAt(selectionStart)) &&
!specialCharsRegex.test(mask.charAt(selectionStart + 1)) &&
mask.slice(0, selectionStart).replace(/[^a-zA-Z0-9]+$/, '').length === length
) {
// if user deletes the last special character
newValue = value;
} else {
Expand All @@ -42,7 +40,7 @@ export const getMaskedValue = (event: React.ChangeEvent<HTMLInputElement>, mask:
maskedValue = value
.replace(specialCharsRegex, '')
.split('')
.reduce((acc: string, c: string) => applyMasking(acc + c, mask), '');
.reduce((acc: string, c: string) => applyMasking(acc + c, mask, selectionStart ?? 0), '');
}

return maskedValue;
Expand Down

0 comments on commit 38bc390

Please sign in to comment.