How to handle the error if `To` number is valid or not?

Issue

What im trying to do is to throw an error message if the user has entered an invalid number.

controller/auth.js

  const otp = await client.verify
    .services(serviceId)
    .verifications.create({ to: phone, channel: "sms" });
  
 // if phone is invalid{
    //return error }

  res.status(200,`The user has been created! Otp has been sent to ${phone} number!`).json({
    success: true,
    data: user,  
    otp: otp,
  });

What condition can I use to check the phone if it’s invalid

Solution

You can use the Twilio Lookup API (it has a free tier) to validate the structural integrity of the entered phone number. You can also use the Lookup API to see what carrier the number is hosted with and if the number is a landline, mobile, or VoiP number (this functionality does have a per lookup fee).

Doing a lookup using the Lookup API on a invalid number format will return a 404 not found and hit the catch block.

client.lookups.v1.phoneNumbers('+1510867531')
                 .fetch({})
                 .then(phone_number => console.log(phone_number))
                 .catch(error => (console.log(`Error: ${error}`)))

Output:

'Error: Error: The requested resource /PhoneNumbers/+1510867531 was not found'

enter image description here

Answered By – Alan

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.