I'm trying to validate this kind of phone number in regEx in React (044) 456-7890
.
Check codesanbox here CLICK HERE
Code
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>
I'm trying to validate this kind of phone number in regEx in React (044) 456-7890
.
Check codesanbox here CLICK HERE
Code
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>
Share
Improve this question
edited Aug 13, 2020 at 4:31
Joseph
asked Aug 13, 2020 at 4:08
JosephJoseph
7,80532 gold badges105 silver badges228 bronze badges
6
- Is the sample number the exact format you want to validate for all inputs? – Tim Biegeleisen Commented Aug 13, 2020 at 4:09
- @TimBiegeleisen yes – Joseph Commented Aug 13, 2020 at 4:10
-
Your current regex
(d{3})s*d{3}-d{4}
is bogus, because you don't escape the metacharacters. It should be corrected to\(\d{3}\)\s*\d{3}-\d{4}
. – Tim Biegeleisen Commented Aug 13, 2020 at 4:30 - @TimBiegeleisen. Tried it but same thing it still is outputting invalid – Joseph Commented Aug 13, 2020 at 4:33
-
/\(\d{3}\)\s*\d{3}-\d{4}/.test("(044) 456-7890")
is working. There is something wrong with JS code and how you are calling the regex API. – Tim Biegeleisen Commented Aug 13, 2020 at 4:34
3 Answers
Reset to default 2^\(\d{3}\)\s\d{3}-\d{4}$
This matches the given format exactly
https://regex101./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"
)
});
To validate the exact number format (044) 456-7890
I would suggest:
\(\d{3}\)\s*\d{3}-\d{4}
Demo
I guess it would be better to use a real phone checking library like: https://github./catamphetamine/libphonenumber-js
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745406360a4626331.html
评论列表(0条)