Random Sog
Random Sog

Reputation: 161

How to validate phone number using Yup but is not required?

I am able to validate if what is typed a phone number using this regexp but it is requiring a phone number to be entered in the input field. I am trying to make phone number optional. When I remove .matches phoneRegExp, it works without being required. I believe it has something to do with the regexp that makes the field turn into required. But I am not sure. Should I do it a different way? thanks


        const phoneRegExp = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/;

const signUpSchema = yup.object().shape({
  username: yup
    .string()
    .min(4, "Need at least 4 characters.")
    .required("Username is required"),
  firstName: yup
    .string()
    .min(2, "Need at least 2 characters.")
    .required("First name is required"),
  lastName: yup
    .string()
    .min(2, "Need at least 2 characters")
    .required("Last name is required"),
  email: yup
    .string()
    .email()
    .required("Email is required"),
  phoneNumber: yup.string()
    .matches(phoneRegExp, "Phone number is not valid")
    .notRequired(),
  password: yup
    .string()
    .min(6, "Password must be at least 6 characters.")
    .required("Password is required"),
  instructorOrClient: yup
    .string()
    .matches(/(instructor|client)/, "Either instructor or client.")
    .required("Please select instructor or client."),
});

Upvotes: 16

Views: 16152

Answers (3)

Shubham Khunt
Shubham Khunt

Reputation: 361

You can modify your regex which will support both phone numbers or the empty string

To match pattern or an empty string, use

^$|phoneRegx

Explanation

  • ^ and $ are the beginning and end of the string anchors respectively. | is used to denote alternates, e.g. this|that.

const phoneRegExp =/^$| ^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/

phoneNumber: yup.string().matches(phoneRegExp, "Phone number is not valid"),

Upvotes: 0

Dhanuka Perera
Dhanuka Perera

Reputation: 1803

Add excludeEmptyString:true to matches. need to be an object.

{
message:"Phone not valid",
excludeEmptyString:true
}

Example

  const PHONE_NO_REGEX = /^[0-9\- ]{8,14}$/
        const signUpSchema = yup.object().shape({
        ...
        phoneNumber: yup.string()
            .matches(PHONE_NO_REGEX, phoneNumber:yup.string().matches(PHONE_NO_REGEX,{message:"not valid phone no",excludeEmptyString:true}))
          
        ...
        });

Upvotes: 25

aturan23
aturan23

Reputation: 5400

You should do .nullable():

const signUpSchema = yup.object().shape({
...
phoneNumber: yup.string()
    .matches(phoneRegExp, "Phone number is not valid")
    .nullable(),
...
});

You can read more about this on docs.

Upvotes: 1

Related Questions