How to validate a cell phone and a home?

-3

I would like to validate the home and mobile phone by adding the parentheses and dash automatically .

>

Mobile

What I would like:

Validate if the cell contains the digit 9 at the beginning and DDD (2 digits), totaling 11 digits. So, validate if it contains 11 digits.

Add the parentheses automatically and dash.

(51) 97654-3389

Residential E:

What I would like:

Validate if it contains the DDD (2 digits), totaling 10 digits. So, validate if it contains 10 digits.

Add the parentheses and dash automatically.

(51) 3456-5043

I researched regex but did not understand 100%.

How could I do this with JavaScript / jQuery?

    
asked by anonymous 02.10.2018 / 18:48

1 answer

2

You can use a regular expression.

  

This is a string that defines a search pattern. It's an algorithm. We can   say that it is a language for locating patterns in text. See: What is a regular expression?

JavaScript has RegExp.prototype.test() , which returns true or false for validation.

The regular expression I use to validate Brazilian phones is as follows:

/^\(\d{2}\) \d{4,5}-\d{4}$/gi
{início da linha}({dois dígitos}) {de quatro a cinco dígitos}-{quatro dígitos}{fim da linha}

This expression will accept phones in the format (XX) XXXX-XXXX and (XX) XXXXX-XXXX .

To test a string against it, you can use test() :

const isValidPhone = (phone) => {
  const brazilianPhoneRegex = /^\(\d{2}\) \d{4,5}-\d{4}$/gi;
  return brazilianPhoneRegex.test(phone);
};

isValidPhone("(41) 99778-2914");
// true

isValidPhone("(411) 99778-2914");
// false

isValidPhone("(41) 9778-2914");
// true

If you want to be more permissive, I would do it another way. He would pick up the input string, pull out anything that is not numeric, and check if it has 10 to 11 digits, which is the format of the two-digit DDD phone. This would look like this:

const isValidPhone = (phone) => {
  const sanitizedPhone = phone.replace(/\D/g,'');
  return sanitizedPhone.length >= 10 && sanitizedPhone.length <= 11;
};

isValidPhone("(41) 99778-2914");
// true

isValidPhone("()41A977B8-----8319");
// true, pois tira todo caractere que não é numérico

For the mask, you can use jQuery, as you suggested yourself. To not reinvent the wheel, there are some questions in Stack Overflow in Portuguese that have already answered it: Phone Mask Using jQuery Mask Plugin

If you want to extend or test the regular expression, I use the site RegExr .

    
02.10.2018 / 19:01