Skip to content

Commit

Permalink
fix: input mask with allowZeroAfterCallingCode props
Browse files Browse the repository at this point in the history
  • Loading branch information
AstrOOnauta committed Nov 20, 2024
1 parent a9ceada commit cfcb0ce
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
2 changes: 1 addition & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ const PhoneInput = forwardRef(
callingCode ? callingCode : countryValue?.callingCode,
countryValue?.cca2,
customMask ? customMask : null,
allowZeroAfterCallingCode
allowZeroAfterCallingCode === false ? false : true
);

if (ref) {
Expand Down
19 changes: 15 additions & 4 deletions lib/utils/getInputMask.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import { countries } from '../constants/countries';

function eliminateZeroAfterCallingCode(phoneNumber, callingCode) {
function startsWithZero(phoneNumber, callingCode) {
const newCode = callingCode.replace('+', '');
return phoneNumber.startsWith('0') ||
return (
phoneNumber.startsWith('0') ||
phoneNumber.startsWith(`${newCode}0`)
? phoneNumber.slice(newCode.length + 1, phoneNumber.length)
);
}

function eliminateZeroAfterCallingCode(phoneNumber, callingCode) {
return startsWithZero(phoneNumber, callingCode)
? phoneNumber.slice(1, phoneNumber.length)
: phoneNumber;
}

Expand Down Expand Up @@ -73,7 +79,12 @@ export default function getInputMask(
? value
: eliminateZeroAfterCallingCode(value, callingCode);

return matrix.replace(/(?!\+)./g, function (a) {
const newMatrix =
allowZeroAfterCallingCode && startsWithZero(value, callingCode)
? '#' + matrix
: matrix;

return newMatrix.replace(/(?!\+)./g, function (a) {
return /[#\d]/.test(a) && i < newValue.length
? newValue.charAt(i++)
: i >= newValue.length
Expand Down

0 comments on commit cfcb0ce

Please sign in to comment.