AngularJs validate input length for multiple lengths

1.1k views Asked by At

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.

2

There are 2 answers

1
Hadi On BEST ANSWER

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>

1
BHAVIK On

try this in you tag

ng-pattern="/^[0-9]{1,16}$/" ng-maxlength="16"