这是我的代码中的一个片段。
let schema = yup.object().shape({
phone: yup
.string()
// regexr.com/6anqd
.matches(/(\+91\ )[6-9]{1}[0-9 ]{4}[0-9 ]{4}[0-9]{3}/, {
message: "Invalid Indian number",
excludeEmptyString: false,
})
.required(),
email: yup.string().required().email(),
password: yup.string().required().min(8),
confirmPassword: yup
.string()
.required()
.oneOf([yup.ref("password")], "Passwords do not match"),
agree: yup
.boolean()
.oneOf(
[true],
"It is essential to accept our Privacy Policy to register.",
),
});
我的正则表达式按照以下格式检查印度电话号码+91 axxx xxx xxx
(其中a
可以是 6 到 9 范围内的数字,x
也可以是 0 - 9)。
我尝试了yup-home,但它无法真正验证我想要的印度号码的范围,另外,包裹导入大小很昂贵。
另外,我在前端使用带有 Formik 的 React 来使用react-phone-input-2进行表单验证
<PhoneInput
country={"in"}
value={values.phone}
name="phone"
onChange={(phone, data, e) => handleChange(e)}
onBlur={(e) => handleBlur(e)}
defaultMask=".... ... ..."
masks={{ in: ".... ... ..." }}
onlyCountries={["in"]}
inputProps={{
name: "phone",
required: true,
autoFocus: true,
}}
disableSearchIcon={true}
disableDropdown={true}
containerClass="mt-1 border h-12 text-sm focus:outline-none block w-full bg-gray-100 dark:bg-transparent border-transparent focus:bg-white"
inputClass="mt-1 border h-12 text-sm focus:outline-none block w-full bg-gray-100 dark:bg-transparent border-transparent focus:bg-white"
inputStyle={{
background: "transparent",
border: "1px solid grey",
height: "3em",
width: "100%",
outline: "none",
}}
buttonStyle={{
height: "3em",
background: "transparent",
outline: "none",
border: "none",
}}
/>
{handleFormikError(errors, touched, "phone")} // returns the span.alert with error message