feat: phone number validation
This commit is contained in:
@ -1,33 +1,20 @@
|
||||
import { CountryCode } from "libphonenumber-js";
|
||||
import { Country } from "@/components/PhoneInput/types";
|
||||
import getFormat from "@/components/PhoneInput/utils/getFormat";
|
||||
import countryOptionsDataMap from "@/components/PhoneInput/utils/countryOptionsDataMap";
|
||||
import { CountryCode, parsePhoneNumberFromString } from "libphonenumber-js";
|
||||
import getPhoneMask from "@/components/PhoneInput/utils/getPhoneMask";
|
||||
|
||||
type InitialDataFromValue = {
|
||||
country: Country;
|
||||
format: ReturnType<typeof getFormat>;
|
||||
localValue: string;
|
||||
format: ReturnType<typeof getPhoneMask>;
|
||||
};
|
||||
|
||||
const getInitialDataFromValue = (
|
||||
value: string | undefined,
|
||||
initialCountryCode: string
|
||||
): InitialDataFromValue => {
|
||||
const defaultValue = {
|
||||
country: countryOptionsDataMap[initialCountryCode],
|
||||
format: getFormat(initialCountryCode as CountryCode),
|
||||
localValue: "",
|
||||
};
|
||||
if (!value) return defaultValue;
|
||||
const phoneNumber = parsePhoneNumberFromString(value);
|
||||
if (!phoneNumber) return defaultValue;
|
||||
if (!phoneNumber.country) return defaultValue;
|
||||
|
||||
return {
|
||||
country: countryOptionsDataMap[phoneNumber.country],
|
||||
localValue: phoneNumber.formatNational(),
|
||||
format: getFormat(phoneNumber.country),
|
||||
country: countryOptionsDataMap[initialCountryCode],
|
||||
format: getPhoneMask(initialCountryCode as CountryCode),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export default getInitialDataFromValue;
|
||||
|
||||
@ -2,14 +2,13 @@ import { CountryCode, getExampleNumber } from "libphonenumber-js";
|
||||
import examples from "libphonenumber-js/examples.mobile.json";
|
||||
import { getCountryCallingCode } from "libphonenumber-js/max";
|
||||
|
||||
export default function getFormat(countryCode: CountryCode) {
|
||||
export default function getPhoneMask(countryCode: CountryCode) {
|
||||
let example = getExampleNumber(
|
||||
countryCode,
|
||||
examples
|
||||
)!.formatInternational();
|
||||
const callingCode = getCountryCallingCode(countryCode);
|
||||
const callingCodeLen = callingCode.length + 1;
|
||||
example = example.slice(callingCodeLen);
|
||||
const mask = example.replace(/\d/g, "0");
|
||||
return { example, mask };
|
||||
example = example.slice(callingCodeLen).trim();
|
||||
return example.replace(/\d/g, "0");
|
||||
}
|
||||
Reference in New Issue
Block a user