在 React 的正则表达式中验证电话号码
Validating Telephone Number in RegEx in React
我正在尝试在 React (044) 456-7890
.
的正则表达式中验证这种 phone 数字
在此处检查 codesanbox CLICK HERE
代码
const telRegExp = "(d{3})s*d{3}-d{4}";
let validateSchema = yup.object().shape({
tel_no: yup.string().matches(telRegExp, "Telephone number is invalid")
});
<InputMask
mask="(999) 999 - 9999"
onChange={handleChange}
onBlur={handleBlur}
>
{() => (
<TextField
label="Telephone Number (Ex: (044) 878 - 3900)"
name="tel_no"
fullWidth
variant="outlined"
helperText={touched.tel_no ? errors.tel_no : ""}
error={touched.tel_no && Boolean(errors.tel_no)}
/>
)}
</InputMask>
为了验证确切的数字格式 (044) 456-7890
我建议:
\(\d{3}\)\s*\d{3}-\d{4}
^\(\d{3}\)\s\d{3}-\d{4}$
这与给定的格式完全匹配
https://regex101.com/r/HBvG3K/6
\( and \) - To escape () characters and match literally
\s - space character. If there can be more or no spaces then add * next to \s
\d{} - decimal numbers(0-9) followed by quantifier.
let validateSchema = yup.object().shape({
tel_no: yup
.string()
.matches(
/^\(\d{3}\)\s\d{3}\s-\s\d{4}/g,
"Telephone number is invalid"
)
});
我想最好使用真正的 phone 检查库,例如:https://github.com/catamphetamine/libphonenumber-js
我正在尝试在 React (044) 456-7890
.
在此处检查 codesanbox CLICK HERE
代码
const telRegExp = "(d{3})s*d{3}-d{4}";
let validateSchema = yup.object().shape({
tel_no: yup.string().matches(telRegExp, "Telephone number is invalid")
});
<InputMask
mask="(999) 999 - 9999"
onChange={handleChange}
onBlur={handleBlur}
>
{() => (
<TextField
label="Telephone Number (Ex: (044) 878 - 3900)"
name="tel_no"
fullWidth
variant="outlined"
helperText={touched.tel_no ? errors.tel_no : ""}
error={touched.tel_no && Boolean(errors.tel_no)}
/>
)}
</InputMask>
为了验证确切的数字格式 (044) 456-7890
我建议:
\(\d{3}\)\s*\d{3}-\d{4}
^\(\d{3}\)\s\d{3}-\d{4}$
这与给定的格式完全匹配
https://regex101.com/r/HBvG3K/6
\( and \) - To escape () characters and match literally
\s - space character. If there can be more or no spaces then add * next to \s
\d{} - decimal numbers(0-9) followed by quantifier.
let validateSchema = yup.object().shape({
tel_no: yup
.string()
.matches(
/^\(\d{3}\)\s\d{3}\s-\s\d{4}/g,
"Telephone number is invalid"
)
});
我想最好使用真正的 phone 检查库,例如:https://github.com/catamphetamine/libphonenumber-js