验证AngularJS中的长度

时间:2015-04-01 08:24:01

标签: angularjs

我有一个用于文本字段的指令,该指令具有如下所示的验证,当文本字段长度小于5个字符时,它应显示一条消息。

 attrs.$observe('useNumberRegex', function( val ) {
                  scope.useNumberRegex = GenericFieldUtils.castBoolean(val, false);
                  if(scope.useNumberRegex)
                  {
                    scope.regExp = /^\d+$/;
                  }
              });

并且指令模板URL指向html,如下所示

      <li ng-if="editable  && (cssClass == 'text_style_filter' || cssClass == 'drp_down_style')" style="float:left;width:42%" class="{{$parent.cssClass}}">
       <input id="{{$parent.uniqueId}}" name="{{$parent.name}}" type="{{$parent.textType}}"  class="field-control {{$parent.numCssClass}}" ng-pattern="$parent.regExp" autocomplete="off"  ng-required="mandatory" ng-maxlength="{{maxLength}}" maxlength="{{maxLength}}" ng-model="$parent.value" ng-disabled="disabled" ng-blur="$parent.onBlur($parent.value)" ng-keyup="$parent.onKeyup($parent.value)" aria-label="{{$parent.ariaLabelInput}}" min="{{min}}" max="{{max}}" validate>
            <div ng-if="$parent.formController.submitController.attempted">
                {{$parent.regExp}}
              <span class="error-message" ng-repeat="error in errors" translate>{{error}}fdsfsdfsdf</span>
            </div>
          </li>

Can you please help me what is going wrong in displaying a message when the length is less than 5 characters long.

1 个答案:

答案 0 :(得分:0)

  1. 您可以使用ng-minlength来实际验证输入的长度。
  2. 您还可以使用正则表达式模式进行验证。而不是/ ^ \ d + $ / use / ^ \ d {5,} $ /