使用角度js验证电话号码

Pra*_*M P 13 javascript angularjs angularjs-validation

想要将电话号码设置为10位,如何使用Angular js执行此操作.

这是我尝试过的:

<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>
Run Code Online (Sandbox Code Playgroud)

但我没有收到验证错误.

rwa*_*ter 13

试试这个:

<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>
Run Code Online (Sandbox Code Playgroud)

  • 我不确定这是否是特定于浏览器的,但在Chrome中,此输入当前将在输入结束时以微小的增量/减量显示.它有小箭头来增加和减少数量. (3认同)

Sil*_*ver 7

检查这个答案

基本上,您可以创建一个正则表达式来满足您的需求,然后将该模式分配给您的输入字段.

或者更直接的方法:

<input type="number" require ng-pattern="<your regex here>">
Run Code Online (Sandbox Code Playgroud)

更多信息@ angular docs here and here(内置验证器)