Validation for Phone type field

Asked

Viewed 4,237 times

1

Personal someone would have some validation for telephone field type?

Where the user cannot place dummy numbers in the field as number sequences (99999 8888 123456) or something like?

  • In your class you can use regular expression, here is a straight explanation of how it works: https://answall.com/questions/46672/como-fazer-uma-express%C3%A3o-regular-for-cell phone- then use mask to format.

4 answers

0


I use the jQuery Mask plugin, to manage my masks.

Code

I just adapted the ending to validate your need.

$(document).ready(function(){
    $('body').on('focus', '.phone', 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, '');
                    if(/\d\d(\d)\1{7,8}/.test(val)){
                        field[0].value = '';
                        alert('Telefone Invalido');
                    }
                }
            }
        };
        $(this).mask(maskBehavior, options);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>

<input type="text" placeholder="Telefone" name="phone" class="phone"/>

Explanation

var maskBehavior = function (val) {
    return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
}

This part checks whether it will be 9 or 8 digits and formats the mask the right way.

options = {
    onKeyPress: function(val, e, field, options) {
        field.mask(maskBehavior.apply({}, arguments), options);

Applies the previous rule whenever a key is pressed.

if(field[0].value.length >= 14){
    var val = field[0].value.replace(/\D/g, '');
    if(/\d\d(\d)\1{7,8}/.test(val)){
        field[0].value = '';
        alert('Telefone Invalido');
    }
}

Here is what you want, when the content has more than 14 characters performs content check.

  • var val = field[0].value.replace(/\D/g, ''); - removes anything that is not typed (just to make it easy).
  • /\d\d(\d)\1{7,8}/ - equal sequential validation, ignore DDD if all digits are equal.
  • \1{7,8} - refers to the previous catch, which should repeat 7 to 8 times

If all this is valid, then perform the if which invalidates the content.

0

No. The most that can be done is a Regex validating the format of the text placed on the phone. For example, this below validates the following formats with country code, DDD and phone with 8 or 9 digits +XX (XX) XXXX-XXXX or +XX (XX) XXXXX-XXXX

/^(?:\+)[0-9]{2}\s?(?:\()[0-9]{2}(?:\))\s?[0-9]{4,5}(?:-)[0-9]{4}$/

An example of how to use this Regex:

var regExp = /^(?:\+)[0-9]{2}\s?(?:\()[0-9]{2}(?:\))\s?[0-9]{4,5}(?:-)[0-9]{4}$/;
var telefone = '+55 (55) 23321-5454';
var resultado = regExp.test(telefone); (retorna true ou false)
  • at least show the use of regex as a mask, not just throw it there

  • can you give me an example?

  • @Leonardomacedo I edited the answer with an example.

0

FOR THE MASK OF INPUT

Try using this plugin, since there is no native resource for this.

By adding it to your project you can use a method in your plugin, the .inputmask and thus set the mask for your input by a reference to its class, id or property name.

Follow a test in Jsfiddle to ensure it works:

$("#test").inputmask({
            mask: "(99)99999-9999",
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js"></script>
<input id="test" type="text"></input>


FOR VALIDATION OF INPUT DATA

As you mentioned in the comments that you also want a validation and it is not something logical, IE, it is something you need for your system and is defined by yourself without integrated logic.

I want there to be a validation in the input where the user cannot type numbers that do not exist as an example: 9999999 888 777 123456789 987654321 11122233 4455566888

Try validation by an array blackList, where all elements of this array will be tested and you will take action if one of these elements der match through regular expression.

Follow an example:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<button onclick="blackListExpressions.forEach(myFunction)">Try it</button>
<p id="demo"></p>
<script>
demoP = document.getElementById("demo");

var blackListExpressions = [/9999/, /8888/, /7777/];
var testeString = '(11)99999-9999';

function myFunction(item, index) {
    if(testeString.match(item)){
    demoP.innerHTML = demoP.innerHTML + "index[" + index + "]: " + "true" + "<br>";

    }
    else{
		demoP.innerHTML = demoP.innerHTML + "index[" + index + "]: " + "false" + "<br>";
    }
}
</script>

  • I have these masks in my system, I really need the field validate the data informed, not to accept 9999 888 etc...

  • @Leonardomacedo so you want there to be validation in the input to not accept repeated numbers?

  • I want there to be a validation in the input where the user cannot type numbers that do not exist as an example: 9999999 888 777 123456789 987654321 11122233 4455566888

  • @Leonardomacedo see if my new example meets your need

0

I don’t know if you might be interested, but I will give you an answer using only validation on the client’s side. However it is not possible to validate sequence numbers in this way. The positive point is that it opens the keyboard of the device for the person to enter the number if she access by mobile for example.

In the example below I used the <input type="tel"> there are several direct HTML validation rules (the detail here is that an advanced user can log in to Dev Tools for example and delete these rules before sending)

First I used a CSS to switch the border of the case is valid or invalid. You can still use icons for this or Tooltips, it goes from your taste and design...

Then I made the rules on <input>

pattern="[0-9]+$"  //O pattern do campo só aceita números
required           //o campo é de preenchimento obrigatório
minlength="9"      //tem que ter no mínimo 9 números
maxlength="14"     //e no máximo 14 números

See example working.

input[type="tel"]:valid {
    border: 2px solid green;
}
input[type="tel"]:invalid {
    border: 2px solid red;
}
<input type="tel" id="telNo" name="telNo" pattern="[0-9]+$" required minlength="9" maxlength="14" size="30" placeholder="apenas numeros, de 9 a 14 caracteres">

How he’s a <input> tel-type it will open the device keyboard: (besides having the correct semantics for the field type!)

inserir a descrição da imagem aqui

Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/tel

Browser other questions tagged

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