表单无效时在Angular中显示错误

时间:2014-05-12 12:14:10

标签: angularjs

Angular中是否有自动方式显示无效表单的错误消息。例如,我有以下内容。它确实运行良好,因为它不允许用户提交,但它没有给用户任何自动反馈,告诉他们需要元素。如果表单在提交时无效,那么字段是否有自动方式来打印字段?

           <div class="form-center">
    <form name="loginform" class="forms" ng-controller="controllers.LoginController">
        <fieldset>  <legend><h3>Account Login</h3></legend>

            <div class="advanced-search-item">
                <label>Username:</label><br /> <input type="text" ng-model="username" name="username" placeholder="username" required><span class="error" ng-show="submitted && loginform.username.$error.required">Required!</span>

            </div>

            <div class="advanced-search-item">
            <label>Password:</label><br /> 
                <input type="password" name="password" ng-model="password" placeholder="password" required><span class="error" ng-show="submitted && loginform.username.$error.required">Required!</span>
            </div>


             <div class="advanced-search-item">
                 <a href="#" class="advanced-search-button submit-button" ng-disabled='!loginform.$valid' ng-click="submitted=true;loginUser()">Login</a>
            </div>


        </fieldset>
    </form>
    </div>

1 个答案:

答案 0 :(得分:2)

您必须添加一些跨距以显示输入字段旁边的错误,如下所示

<span class="error" ng-show="submitted && loginform.username.$error.required">Required!</span>

<span class="error" ng-show="submitted && loginform.password.$error.required">Required!</span>

希望您可以将此文本保留为红色,下面是CSS

.error {
    padding-left:10px;
    color: #F00;
}

提交表单时,如果有错误,将显示上面的跨度

希望这有帮助