Search code examples
node.jsbotframework

How to validate phone number in bot framework?


I'm using following code to get user input for a phone number. I want to validate user input and if it is incorrect, need to ask the user to enter again.

[function (session, results, next) {
    builder.Prompts.text(session, 'I will also need to know your contact number.');
}
,function (session, results, next) {
    session.userData.contactNo = results.response;
    next();
}]

I tried this example, but it gives a warning saying it is deprecated. Appreciate any help regarding the correct way to do this(without using the deprecated method). My phone number regex is ^[689]\d{3}\s?\d{4}$


Solution

  • There is an interesting sample in the documentation:

    bot.dialog('/phonePrompt', [
        function (session, args) {
            if (args && args.reprompt) {
                builder.Prompts.text(session, "Enter the number using a format of either: '(555) 123-4567' or '555-123-4567' or '5551234567'")
            } else {
                builder.Prompts.text(session, "What's your phone number?");
            }
        },
        function (session, results) {
            var matched = results.response.match(/\d+/g);
            var number = matched ? matched.join('') : '';
            if (number.length == 10 || number.length == 11) {
                session.endDialogWithResult({ response: number });
            } else {
                session.replaceDialog('/phonePrompt', { reprompt: true });
            }
        }
    ]);
    

    Here you can see that in the function handling the result, they are performing some checks and then if not valid they are doing a replaceDialog with a reprompt parameter.

    You may try the same here with your business logic (ie: doing your regex check instead of the number length check in the sample)