Aanchal Aanchal - 4 months ago 7
AngularJS Question

Add validation for input field for either 7 or 9 digits in AngularJS

I am trying to add validation in my input field so that it can accept either 7 or 9 digits but I could not find any way to do this. In my code, I added

ng-minlength=7
and
ng-maxlength=9
but it does not solve my purpose .

I want to add either 7 or 9 digits only so If I enter 8 digits in my box it should show an error. Below code I used but it does not fulfill my requirement-

<div class="form-group" ng-class="{ 'has-error' : myForm.num.$invalid && (myForm.$submitted || myForm.num.$touched ) || myForm.num.$error.minlength || myForm.num.$error.maxlength}">

<label for="UserName" style="color:#767676" class="" ng-hide="myForm.num.$invalid && (myForm.$submitted || myForm.num.$touched || myForm.num.$error.minlength || myForm.num.$error.maxlength)">Number</label>
<label class="error_message_text" ng-show="myForm.num.$invalid && (myForm.$submitted || myForm.num.$touched || myForm.num.$error.minlength || myForm.num.$error.maxlength)">
Please enter the number of either 7 or 9 digits
</label><br>
<input type="text" numbers-only name="num" class="form-control" ng-class="" ng-minlength="7" ng-maxlength="9" ng-model="user.name" ng-required='!user.memNo' required/>

</div>


I have created a plunker here-
https://plnkr.co/edit/S39AZNzlHa2vW6uQDuov?p=preview

Can anybody help me in my validations?

Answer

Use

ng-pattern="/^\d{7}$|^\d{9}$/"