Validation Telephone Field

Asked

Viewed 12,517 times

6

Guys, I need some help from you.

I have a telephone mask, which validates the fields 00000 11111 2222 3333 in sequence.

 $('body').on('focus', '.celular', function () {
        var maskBehavior = function (val) {
            return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
        },
        options = {
            onKeyPress: function (val, e, field, options) {
                field.mask(maskBehavior.apply({}, arguments), options);

                if (field[0].value.length >= 14) {
                    var val = field[0].value.replace(/\D/g, '');
                    var intRegex = /[0-9 -()+]+$/;
                    if (/\d\d(\d)\1{7,8}/.test(val)) {
                        field[0].value = '';
                        notif({
                            msg: "<b>Atenção!</b> Este número está invalido!",
                            type: "error",
                            position: "center"
                        });
                    }
                }
            },
            clearIfNotMatch: true
        };
        $(this).mask(maskBehavior, options);
    });

Only I’m not getting her to validate this sequence 123456789 etc...

Could someone help me with this?

  • Here has a very good answer about it. It doesn’t help you?

  • Wouldn’t it be better to do this through a regex? ([0-9]{2})[0-9]{9}$ validates any String in the format (DDD)Number, including parentheses. If you want to validate a Landline phone, you have to start with 3, then it would be ([0-9]{2})3[0-9]{7}$ and if it is a Landline phone starts with 9, then, ([0-9]{2})9[7-9][0-9]{7}$

  • @Marcosdeandrade What would this look like in regex? only replace the value that is in intRegex ?

  • @bio I will test this your validation

  • The site of Mozilla has an excellent reference on Regular Expressions, suggest take a look. I suggest also look at the site Regexr.com to validate its regex, it is excellent and has a very good references on the side.

  • @I think AP is trying to validate an invalid number. That is, numbers that the user puts as (11) 1111-11111. Unfortunately the regex he is using does not validate (12) 3456-7890, for example. I think that’s it, no?

  • @bio that’s right, the sequence of (11) 1111-11111 is checking, what it doesn’t check is the sequence of '(12) 3456-7890'

  • Is he typing the dash? The regex I wrote doesn’t use the dash, so it wouldn’t even validate. Let me understand the problem, you want to validate numbers fixed and mobile phones, Only Fixed or Only mobile? If you want to validate FIXED and CELLULAR at the same time, the regex has to use the expression OR, ai é mais difícil de montar.

  • @Marcosdeandrade I need it to validate both because if I put the sequence (01) 2345-6789 is fixed if I put (01) 23456-7890 is cellular only that the two are invalid, gave to understand what I mean?

  • Se você não for digitar o traço, utilize a regex ^([0-9]{2})((3[0-9]{7})|(9[0-9]{8}))$&#xA;&#xA;Se você for digitar o traço, utilize a regex ^([0-9]{2})((3[0-9]{3}-[0-9]{4})|(9[0-9]{3}-[0-9]{5}))$

  • @Would this regex look like this? var intRegex = / ([0-9]{2})(3[0-9]{3}-[0-9]{4})|(9[0-9]{3}-[0-9]{5}))$/; or is it wrong? sorry question do not understand much about regex

  • I put the regex just above your comment. I’m doing a post with the answer. As you are typing a String it has to have double quotes starting and ending, or you type straight into New Regexp(regex)

  • @Marcosdeandrade Ok, I’ll be waiting if post, man thanks so much for your help

Show 8 more comments

1 answer

5

If you want to validate a number, use a Regular Expression. The website of Mozilla presents a excellent article on the subject, and the website Regexr is great for validating regular expressions.

In your case, if you type the number with the parentheses and strokes, the expression will be

^\\([0-9]{2}\\)((3[0-9]{3}-[0-9]{4})|(9[0-9]{3}-[0-9]{5}))$

Explaining:

  • The symbol ^ indicates the beginning of a String, and $ indicates the end of a String. This means that there can be no whitespace at the beginning or end of your String. Or you can clear it using a call to the TRIM function, or you can take the $

  • \\( e ) represent the specific character input ( and ). It is used because it "escapes" the character instead of making it have its normal function

  • The symbol - does not need to be escaped with because it has no other function in regular expressions.

  • [0-9]{2} accepts two of any value in sequence between 0 and 9 (from 00 to 99)

  • ( (Expression) | (Expression) Represents a Logical OR, where it validates an expression OR another, or BOTH.

If you type without the strokes, the expression will be

^\\([0-9]{2}\\)((3[0-9]{7})|(9[0-9]{8}))$

I believe that in both cases you can assign the regular expression to a variable and initialize a Regexp, or start directly through an attribute passage to Regexp

var expressao = '^\\([0-9]{2}\\)((3[0-9]{3}-[0-9]{4})|(9[0-9]{3}-[0-9]{5}))$';
var regex = new RegExp(expressao);

OR

var regex = new RegExp('^\\([0-9]{2}\\)((3[0-9]{3}-[0-9]{4})|(9[0-9]{3}-[0-9]{5}))$');

After creating the regular expression you can validate it using the match method that regex has.

var telefone = '(31)3233-4343';
var regex = new RegExp('^\\([0-9]{2}\\)((3[0-9]{3}-[0-9]{4})|(9[0-9]{3}-[0-9]{5}))$');
regex.test(telefone);

In function form:

function validPhone (phone) {
    var regex = new RegExp('^\\([0-9]{2}\\)((3[0-9]{3}-[0-9]{4})|(9[0-9]{3}-[0-9]{5}))$');
    return regex.test(phone);
}

validPhone('(31)3534-2323'); //Valido
validPhone('(31)9923-23288'); //Valido
validPhone('(31)9923-3288'); //Invalido
validPhone('(31)2323-5443'); //Invalido

Alternatively, you can use a library that applies a mask directly in the view in a reactive way (as well as React, angular and Vue, for example, have applications) and the user would only type the numbers; it would be stored without the characters in your database or data structure, which would facilitate its manipulation, and the number would be formatted automatically only when presented to the view (ideal situation).

Example: 319938-42838 would be formatted for (31)9938-42838.

Edit: To validate a DDD between 11 and 99:

var telefone = '(31)9923-99288';
var regex = new RegExp('^\\(((1[1-9])|([2-9][0-9]))\\)((3[0-9]{3}-[0-9]{4})|(9[0-9]{3}-[0-9]{5}))$'); 
if (regex.test(telefone)) { 
    console.log("Válido");
}
else console.log("Inválido");

You can test online through of this tool.

Edit: You are using the Jquery Mask Plugin and, in it, you are cleaning the code of the parentheses and strokes used by the user, and applying the mask directly by the amount of numbers that the user has typed. Therefore, Regex will not work because it is checking for traces or parentheses.

To work this way, you can use the following method:

function validatePhone (phone) {
    var regex = new RegExp('^((1[1-9])|([2-9][0-9]))((3[0-9]{3}[0-9]{4})|(9[0-9]{3}[0-9]{5}))$'); 
    return regex.test(phone);
}

var telefone = '31992399288';
validatePhone (telefone);

In this case, the user type or not the parentheses and the dash will not modify at all the result of the code since it clears the characters that are not numbers anyway through the String filter.replace.

  • Where I would use this expression within the @Marcos Method ?

  • Depends, do you want to Validate or Validate and Replace the input with the mask? Honestly, I don’t know advanced enough javascript to explain the validation and simultaneous replacement, but I found an article who seems to treat about it

  • only validate the number

  • If you just want to validate, you can do any function within its scope that accepts a string as argument and have it return True or False to validate (the return of regex.test)

  • Beauty understood, just one more question, I need to put the expression you wrote between / Expression / correct? or the way you put it is correct?

  • I edited the answer with an example in function form. No need to put between / Expression / because Regexp already mounts an expression based on a given String.

  • I added an explanation of the use of characters in the regular expression if you have a little interest in understanding their use :)

  • I understood and I’m already passing this on to my system, just wanted to ask you a question about Regular Expressions. My doubt is this, in this expression you created, could you explain to me why? (3[0-9]{3}-[0-9]{4}) I understand the first of the sequence numbers 0-9, this one I reported, are you doing any calculations or anything like that? or it’s just the separation of the number through the back ?

  • The parentheses delimit a scope, a sequence of characters that must be evaluated. Therefore, ( Expression ) separates what is inside from what is outside. 3 [0-9]{3} indicates that I will validate the number if it starts with character 3 and is followed by any other 3 characters between 0 and 9, therefore 3000 and 3999. After, the symbol - indicates that I must validate if after the first 4 characters I have a dash, and then with [0-9]{4} valid if there are 4 more characters between 0 and 9 in sequence (therefore, 0000 to 9999). The result would be 3ddd-dddd (where d any digit between 0 and 9).

  • If you want examples of each of the elements of the expression I used, the site Regexr that I Linkei at the beginning of the post has a side section that explains each and gives examples, is very interesting and helps a lot when doubts arise.

Show 6 more comments

Browser other questions tagged

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