【发布时间】:2022-07-10 00:03:23
【问题描述】:
我正在使用react-phone-number-input 库。不需要输入电话号码,但如果该号码存在,我希望在发送表单之前对其进行验证。
如果cellphone 字段在提交表单时是原始的/保持不变,则isValid 接受undefined(有效状态)。
如果国家代码立即更改(没有实际输入号码)isValid 接受所选国家的呼叫代码(例如瑞典的 +46)。这仍然是一个完全有效的案例。
当在isValid 函数中访问时,phoneCountryCode 始终保存先前选择的值。因此,经过验证的电话号码和当前的国家代码之间总是存在差异。我不确定问题是否是特定于库的,也许是我的错误。如何消除上述差异?
我发了reproduction on CodeSandbox。
import PhoneInput, {
parsePhoneNumber,
getCountryCallingCode
} from "react-phone-number-input";
const [phoneCountryCode, phoneCountryCodeSetter] = useState('DE');
<Controller
name="cellphone"
rules={{
validate: {
isValid: value => {
if(value) {
const callingCode = getCountryCallingCode(phoneCountryCode);
if(! new RegExp(`^\\+${callingCode}$`).test(value)) {
// The parsePhoneNumber utility returns null
// if provided with only the calling code
return !!parsePhoneNumber(value);
}
}
return true;
}
}
}}
control={control}
render={({ field }) => (
<PhoneInput
{...field}
onCountryChange={(v) => phoneCountryCodeSetter(v)}
limitMaxLength={true}
international={true}
defaultCountry="DE"
/>
)}
/>
【问题讨论】: