Here's a snippet from my code.
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.",
),
});
My regex checks for Indian Phone numbers following the format, +91 axxx xxx xxx
(where a
can be a digit in the range 6 to 9 and x
can be 0 - 9).
I tried yup-home but it was not able to actually verify the range for the Indian Number I wanted, plus, the package import size was costly.
Also, I'm using React with Formik at the frontend for form validation with 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