0

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>
Joseph
  • 7,042
  • 23
  • 83
  • 181

3 Answers3

2
^\(\d{3}\)\s\d{3}-\d{4}$

This matches the given format exactly

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"
    )
});
rootkonda
  • 1,700
  • 1
  • 6
  • 11
  • Pls check my codesanbox. It still won't work. https://codesandbox.io/s/tel-no-regex2-q4c6x?file=/src/PhoneForm.jsx – Joseph Aug 13 '20 at 04:25
  • Thanks. Could you the meaning of these `/^\` and `/g` ?. – Joseph Aug 13 '20 at 04:45
  • `/ /g` - Thats just to enclose the regex and 'g' is a global identifier, useful when you have multiple strings to match. May not be required for you. ^ and $ represents the beginning and end of string. – rootkonda Aug 13 '20 at 04:51
0

To validate the exact number format (044) 456-7890 I would suggest:

\(\d{3}\)\s*\d{3}-\d{4}

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

I guess it would be better to use a real phone checking library like: https://github.com/catamphetamine/libphonenumber-js

wookieb
  • 4,099
  • 1
  • 14
  • 17