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 .