pkt pkt - 1 month ago 5
AngularJS Question

Regular expression to validate cel number format brazil

In brazil, all cel number has a 9 digit more two digits by area code. But, the third number begin with 9.

Ex: 11 9 65656565 or 11 9 58974512 or 21 9 63259814

So, i need to create a regex to validate this format. I made this, but do not work:

ng-pattern="/^[1-9]\d9?\d{8}$/"
. Below, my code(html). I use AngularJS(version 1).

<label for="celular" class="col-sm-1 control-label">Celular</label>
<div class="col-sm-2">
<input id="celular" class="form-control input-sm" name="celular" type="tel" ng-model="vm.data.celular" ng-required="true"
ng-pattern="/^[1-9]\d9?\d{8}$/" />
<!--@"^\(?\d{2}\)?[\s-]?[\s9]?\d{4}-?\d{4}$"-->
<div class="message" ng-messages="form.celular.$error" ng-show="form.celular.$touched">
<div ng-message="required">Por favor, preencha o campo celular!</div>
<!--<div ng-message="minlength">O campo celular deve ter no m&iacute;nimo 11 caracteres.</div>
<div ng-message="maxlength">O campo celular deve ter no m&aacute;ximo 11 caracteres.</div>-->
<div ng-message="pattern">Formato de celular inválido Ex:11988887777</div>
</div>
</div>


In my input text accepts only number.

This is the error message:
enter image description here

Answer

The pattern for the described requirement should be :

/^[1-9]{1}\d{1}\s?[9]{1}\s?\d{8}$/

<input id="celular" class="form-control input-sm" name="celular" type="text"
    ng-model="vm.data.celular" ng-required="true" ng-pattern="/^[1-9]{1}\d{1}\s?[9]{1}\s?\d{8}$/"
/>

REGEX Explained :

1-9 a single character in the range between 1 (ASCII 49) and 9 (ASCII 57)

{1} Quantifier — Matches exactly 1 times

\d matches a digit (equal to [0-9])

{1} Quantifier — Matches exactly 1 times

\s matches any whitespace character(equal to [\r\n\t\f\v ])

? Quantifier — Matches between zero and one times, as many times as possible

9 matches the character 9 literally

\s matches any whitespace character(equal to [\r\n\t\f\v ])

? Quantifier — Matches between zero and one times, as many times as possible

\d{8} matches a digit (equal to [0-9])

{8} Quantifier — Matches exactly 8 times

Please check if it solves your issue

Comments