You can use a regular expression.
It is a string that defines a search pattern. It is an algorithm. We can
say that it is a language for localization of patterns in text. See: What is a regular expression?
Javascript has the RegExp.prototype.test()
, returning true
or false
for its 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 the 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’d do it another way. It would take the input string, take out everything that is not numerical and check if it has 10 to 11 digits, which is the phone format with two-digit DDD. That 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. To not reinvent the wheel, there are some questions in the 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 a lot Regexr.
To use regex you need to define the format of the numbers. Any different character that can vary in the format invalidates the regex.
– Sam