0

I have an input that should validate only if input length is 11 or 14. Is there any way of achieve this without create a directive?

There's one more thing:

I'm using a mask that formats the input as this:
(when 11) 000.000.000-00
(when 14) 00.000.000/0000-00

the pattern should ignore '.' and '/'

Thanks.

tfuelber
  • 85
  • 1
  • 9
  • 1
    Can you share your code snippet? Because it is possible but we must know how you have written the code – Vish Sep 01 '17 at 13:13

2 Answers2

1

Try use ng-pattern

 /^([0-9]{11}|[0-9]{14})$/

// Code goes here

var app = angular.module('app', []);
app.controller('FirstCtrl', function($scope) {

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="FirstCtrl as vm">
  <form name="form">
    <input type="text" name="name" ng-model="name" ng-pattern="/^([0-9]{11}|[0-9]{14})$/">

    <span ng-show="form.name.$error.pattern">Not valid!</span>
  </form>
</div>
Hadi J
  • 16,989
  • 4
  • 36
  • 62
  • 1
    This helped me, but I had to make some adjusts: First, I used just `pattern`attribute instead of `ng-pattern`, because ng-pattern requires an expression. Second, I updated the regex to match the two masks o my input. This is helpful in brazil for the ids CNPJ and CPF. `pattern="^([0-9]{3}\.[0-9]{3}\.[0-9]{3}\-[0-9]{2})|([0-9]{2}\.[0-9]{3}\.[0-9]{3}\/[0-9]{4}\-[0-9]{2})$"` – tfuelber Sep 01 '17 at 16:52
0

try this in you tag

ng-pattern="/^[0-9]{1,16}$/" ng-maxlength="16"
BHAVIK
  • 890
  • 7
  • 35
  • 1
    This doesn't answer the specifics of the question, since it would accept entries of lengths other than 11 or 14, and doesn't handle the / and . characters. – Bob Dalgleish Sep 01 '17 at 15:01