ng-minlength角度形式验证

时间:2016-06-24 15:49:49

标签: angularjs forms validation angularjs-forms

Angular似乎没有在下面的代码中引发minLength或maxLength错误...但是所需的错误(以及电子邮件错误)正在运行。我知道ng-minlength和ng-maxlength正在工作,因为输入框正在改变它的CSS。 <span>内的文字不适用于最小或最大错误。

请参阅下面的密码输入:

<section class="row" data-ng-controller="AuthenticationController">
<h3 class="col-md-12 text-center">Sign Up</h3>
<div class="col-xs-offset-2 col-xs-8 col-md-offset-5 col-md-2">
    <form name="userForm" data-ng-submit="userForm.$valid &amp;&amp; signup()" class="signin form-validate" novalidate autocomplete="off">
        <fieldset>
            <div class="form-group">
                <span ng-show="userForm.email.$dirty &amp;&amp; userForm.email.$error.required" class="text-danger">This field is required</span>
                <span ng-show="userForm.email.$dirty &amp;&amp; userForm.email.$error.email" class="text-danger">This field must be a valid email address</span>
            </div>
            <div class="form-group">
                <label for="username" class="control-label">Username</label>
                <input type="text" id="username" name="username" class="form-control" data-ng-model="credentials.username" placeholder="Username">
            </div>
            <div class="form-group">
                <label for="password" class="control-label">Password</label>
                <input type="password" id="password" name="password" class="form-control" required data-ng-model="credentials.password" ng-minlength="8" ng-maxlength="24" placeholder="Password">
                <span ng-show="userForm.password.$dirty &amp;&amp; userForm.password.$error.required" class="text-danger">This field is required</span>
                <span ng-show="userForm.password.$dirty &amp;&amp; userForm.password.$error.minLength" class="text-danger">Please use a password of at least 8 characters</span>
                <span ng-show="userForm.password.$dirty &amp;&amp; userForm.password.$error.maxLength" class="text-danger">The charactar limit for passwords is 24</span>
            </div>
            <div class="text-center form-group mt">
                <button type="submit" class="btn btn-large btn-primary">Sign up</button>&nbsp; or&nbsp;
                <a href="/#!/page/signin" class="show-signup">Sign in</a>
            </div>
            <div data-ng-show="error" class="text-center text-danger">
                <strong data-ng-bind="error"></strong>
            </div>
        </fieldset>
    </form>
</div>

对这里出了什么问题的想法?

2 个答案:

答案 0 :(得分:1)

这只是语法错误:userForm.password.$error.minLength应该是userForm.password.$error.minlength(大小写)。

答案 1 :(得分:0)

您应该在&amp;&amp;表达式中将&&更改为ng-show,您必须在控制台中收到错误。

更新后的ng-show版本如下所示。

ng-show="userForm.password.$dirty && userForm.password.$error.required"

另一种更方便的方法是使用ng-messages指令,根据表格和&amp ;;显示和隐藏验证消息。其字段有效性