AngularJS ng-minlength ng-required不起作用

时间:2016-12-02 13:01:10

标签: javascript angularjs

我是AngularJS的新手。我想为输入设置验证,例如最小长度为5,最大长度为6。

我必须将5到6位数字设置到我的文本框中。

为此,我使用下面的代码,但它无法正常工作

<div class="input-wrap lg-input">
    <input type="text" name="num" class="form-input" placeholder="Enter 5-6 digits" ng-minlength="5" maxlength="6"
        ng-model="profInfo.Number" ng-required="true">
    <div class="error" ng-show="profInfoForm.$submitted || profInfoForm.num.$touched">
        <span ng-show="profInfoForm.num.$error.required">Required Field</span>
        <span ng-show="profInfoForm.num.$error.minlength">Invalid input</span>
    </div>
</div>
<div class="button-ctr">
    <button class="button" ng-class="profInfoForm.$valid ? 'active' : 'disable'">Next</button>
</div>

目前的工作方式如下:

当文本框为空并且我单击“下一步”按钮时,它显示正确的必填字段错误消息。

我输入的数字不能超过6位。

当我在文本框中键入1位数字并单击按钮时,它显示错误的必填字段错误消息。

当我输入第5位数字时,它显示错误输入错误信息。

我使用的是AngularJS v1.5.5。

2 个答案:

答案 0 :(得分:0)

ng-show="profInfoForm.$submitted || profInfoForm.num.$touched"更改为ng-show="(profInfoForm.num.$dirty || submitted)"

<input type="text" name="num" class="form-input" placeholder="Enter 5-6 digits" minlength="5" maxlength="6" ng-model="profInfo.Number" ng-required="true">
    <div class="error" ng-show="(profInfoForm.num.$dirty || submitted)">
      <span ng-show="profInfoForm.num.$error.required">Required Field</span>
      <span ng-show="profInfoForm.num.$error.minlength">Invalid input</span>
    </div>
  </div>

查看demo

答案 1 :(得分:0)

1)试试这个 -

<input type="text" name="num" class="form-input" placeholder="Enter 5-6 digits" ng-minlength="5" ng-maxlength="6" ng-model="profInfo.Number" required>
    <div class="error" role="alert">
       <span ng-show="profInfoForm.num.$error.required">Required Field</span>
       <span ng-show="profInfoForm.num.$error.minlength">Too Short!</span>
       <span ng-show="profInfoForm.num.$error.maxlength">Too Long!</span>
    </div>

2)但我会更喜欢以下解决方案进行角度形式验证。

<form role="form" name="FORMNAME" ng-submit="vm.submitForm(formData)" novalidate>        
  <div class="form-group form-md-line-input" ng-class="{ 'has-error' : FORMNAME.num.$invalid && !FORMNAME.num.$pristine}">
     <label class="col-md-3 control-label">Number <span style="color:red;">*</span></label>
     <div class="col-md-8">
        <input type="text" class="form-control" name="num" ng-model="formData.number" placeholder="Enter 5-6 digits" ng-minlength="5" ng-maxlength="6" required>
        <span class="help-block" ng-show="FORMNAME.num.$error.required">Please enter name</span>
        <span class="help-block" ng-show="FORMNAME.num.$error.minlength">Too Short!</span>
        <span class="help-block" ng-show="FORMNAME.num.$error.maxlength">Too Long!</span>
     </div>
  </div>
</form>

使用bootstrap“has-error”类,如果任何验证失败,你的元素将变成红色,“has-error”类适用于control-label,form-control类。

“novalidate”将阻止chrome html5验证。