Phone field validation with js

Asked

Viewed 112 times

0

I’m trying to validate the phone of a form defined by RD Station and this rule of mine isn’t working, some hint or something I’m doing wrong?

Follow the form link: https://materiais.onsafety.com.br/demonstracao-modulo-de-inspecao/

function validaTelefone(){
            var telefone = document.getElementById('personal_phone');
            if (telefone.value.lenght > 17){
                alert('Insira um telefone válido. Ex: (99)99999-9999');
                telefone.focus();
                telefone.value = "";
                return false;
            }
}

1 answer

1

There are several ways. I suggest you look for existing questions/answers.

A form in code: - separate the string into specific fields.

 .filter('telefone', function() {
            /*
            Formata numero do telefone como: (xx) xxxx-xxxx ou (xx) xxxxx-xxxx

            */

            return function (number) {
                /*
                @param {Number | String} number - Number that will be formatted as telephone number
                Returns formatted number: (##) ####-#### or (##) #####-####
                    if number.length < 4: ###
                    else if number.length < 7: (###) ###

                */
                if (!number) { return ''; }

                number = String(number);

                // Will return formattedNumber.
                // If phonenumber isn't longer than an area code, just show number
                var formattedNumber = number;

                // if the first character is '1', strip it out and add it back


                var area, front, end;
                if (number.length == 10){
                    // # (##) ####-#### as c (area) front-end
                    area = number.substring(0,2);
                    front = number.substring(2, 6);
                    end = number.substring(6, 10);
                }
                else
                {
                    // # (##) #####-#### as c (area) front-end
                    area = number.substring(0,2);
                    front = number.substring(2, 7);
                    end = number.substring(7, 11);
                }

                if (front) {
                    formattedNumber = ( "(" + area + ") " + front);
                }
                if (end) {
                    formattedNumber += ("-" + end);
                }
                return formattedNumber;
            };
        })

Browser other questions tagged

You are not signed in. Login or sign up in order to post.