Validate phone number using angular js

Praveen M P picture Praveen M P · Jan 16, 2015 · Viewed 103.3k times · Source

Want to set phone-number to 10 digits, How can I do this using Angular js.

This is what I have tried:

<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
  <div class="form-group" ng-class="{'has-error': registration.phone.$error.number}">
    <label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
    <div class="col-sm-9">
      <input type="number" 
             class="form-control" 
             ng-minlength="10" 
             ng-maxlength="10"  
             id="inputPhone" 
             name="phone" 
             placeholder="Phone" 
             ng-model="user.phone" 
             ng-required="true">
      <span class="help-block" 
            ng-show="registration.phone.$error.required && 
                     registration.phone.$error.number">
                     Valid phone number is required
      </span>
      <span class="help-block" 
            ng-show="((registration.password.$error.minlength || 
                      registration.password.$error.maxlength) && 
                      registration.phone.$dirty) ">
                      phone number should be 10 digits
       </span>
    </div>
  </div>
</form>

But I am not getting the validation error.

Answer

rwacarter picture rwacarter · Jan 16, 2015

Try this:

<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
    <div class="form-group" ng-class="{'has-error': registration.phone.$error.number}">
        <label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
        <div class="col-sm-9">
            <input type="number" 
                   class="form-control" 
                   ng-minlength="10" 
                   ng-maxlength="10"  
                   id="inputPhone" 
                   name="phone" 
                   placeholder="Phone" 
                   ng-model="user.phone"
                   ng-required="true">
            <span class="help-block" 
                  ng-show="registration.phone.$error.required || 
                           registration.phone.$error.number">
                           Valid phone number is required
            </span>
            <span class="help-block" 
                  ng-show="((registration.phone.$error.minlength ||
                           registration.phone.$error.maxlength) && 
                           registration.phone.$dirty) ">
                           phone number should be 10 digits
            </span>