ProPhoneInput: fix validation and value

This commit is contained in:
2025-11-13 14:33:41 +03:00
parent 0764d3a641
commit a29aa896e0
4 changed files with 65 additions and 48 deletions

View File

@@ -5,15 +5,21 @@ import { useTranslation } from "react-i18next";
import PhoneInput from "react-phone-input-2";
import { useAppSelector } from "redux/hooks";
import { ProBlack1 } from "ThemeConstants";
import { PhoneNumberUtil } from "google-libphonenumber";
import useFormInstance from "antd/es/form/hooks/useFormInstance";
interface ProPhoneInput extends TitleProps {
phone: string;
setPhone: (phone: string) => void;
propName?: string
label?: string
propName?: string;
label?: string;
getValueCallback?: (value: string) => void;
}
const ProPhoneInput: FunctionComponent<ProPhoneInput> = ({ phone, setPhone, propName, label }) => {
const ProPhoneInput: FunctionComponent<ProPhoneInput> = ({
propName,
label,
getValueCallback,
}) => {
const form = useFormInstance();
const { t } = useTranslation();
const { themeName } = useAppSelector((state) => state.theme);
const { isRTL } = useAppSelector((state) => state.locale);
@@ -23,25 +29,30 @@ const ProPhoneInput: FunctionComponent<ProPhoneInput> = ({ phone, setPhone, prop
name={propName}
label={label}
rules={[
{ required: true, message: "" },
{ required: true, message: t("validation.phoneRequired") },
{
validator: (_, value) => {
if (!value || value.length <= 3) {
return Promise.reject(new Error(""));
}
// Initialize the PhoneNumberUtil instance
const phoneUtil = PhoneNumberUtil.getInstance();
if (
value &&
!phoneUtil.isValidNumber(
phoneUtil.parseAndKeepRawInput(`+${value}`),
)
)
return Promise.reject(new Error(t("validation.invalidPhone")));
return Promise.resolve();
},
},
]}
normalize={(value) => {
if (value && setPhone) {
setPhone(value);
}
return value;
}}
>
<PhoneInputWrapper
phone={phone}
onChange={(value) => {
form.setFieldValue(propName, value);
getValueCallback?.(value);
}}
phone={form.getFieldValue(propName)}
themeName={themeName}
isRTL={isRTL}
placeholder={t("login.mobileNumber")}
@@ -52,8 +63,17 @@ const ProPhoneInput: FunctionComponent<ProPhoneInput> = ({ phone, setPhone, prop
);
};
export const PhoneInputWrapper = ({ phone, themeName, isRTL, placeholder, value, onChange, propName, label }: {
phone: string;
export const PhoneInputWrapper = ({
phone,
themeName,
isRTL,
placeholder,
value,
onChange,
propName,
label,
}: {
phone?: string;
themeName: string;
isRTL: boolean;
placeholder: string;
@@ -106,7 +126,6 @@ export const PhoneInputWrapper = ({ phone, themeName, isRTL, placeholder, value,
autoComplete: "tel",
type: "tel",
inputMode: "numeric",
pattern: "[0-9]*",
}}
/>
</div>