AngularJS表单验证组错误消息

时间:2015-07-16 13:48:02

标签: javascript jquery html angularjs

在angularJs FORM SUBMIT 中,如何在页面底部的一个div中显示所有验证消息。例如:

<div id="err-msg"> <!-- error message will come here --></div>

我引用了文档,但所有文档都显示在文本框下方

<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="alert alert-danger">Enter a valid email.</p>

如何编写一个区域将所有邮件绑定到同一个地方(避免使用此userForm.email.$invalid

注意我试过了ng-message但不清楚任何人帮助我。请参考以下代码,了解正常的HMTL jQuery错误显示,如需要使用AngularJS

HTML

<div id="main">
<form> <div><input id="email_txt" type="text" name ="email" value="" > </div>
<div><input id="pass_txt" type="password" name ="password" value="" > </div>
<div><input id="validate_btn" type="submit" value="Validate" > </div>
</form>
</div>
<div id="err-msg"> <!-- error message will come here --></div>

jQuery的:

$('#main').on('click', '#validate_btn', function() { 
 if($('#email_txt').val().length == 0){
$('#err-msg').val("Please enter emailid!");
}else if($('#pass_txt').val().length == 0){
$('#err-msg').val("Please enter password!");
}
...
...
else{
  alert("Good");
}
});

AngularJS当前代码:

<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<div class="form-group">
  <label>Username</label>
  <input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8">
   <p ng-show="userForm.username.$error.minlength" class="help-block">Username is too short.</p>
   <p ng-show="userForm.username.$error.maxlength" class="help-block">Username is too long.</p> </div> 
   <input type="email" name="email" class="form-control" ng-model="email">
   <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p>
   <button type="submit" class="btn btn-primary">Submit</button>
<form>

app.js

.controller('validatectrl',['$scope',function($scope){
     $scope.submitForm = function(isValid) {
     // check to make sure the form is completely valid
     if (isValid) {
         alert('Good');
     }

    };
 }]);

如何改写?

1 个答案:

答案 0 :(得分:0)

如果表单无效,错误将存储在对象$scope.form.$error中。请检查此JSFiddle的控制台。从表单上的$error属性中,您可以填充错误消息。

angular.module('Joy', [])
    .controller('FormCtrl', ['$scope', function ($scope) {
        $scope.user = {};
        $scope.submit = function () {
            console.log($scope.userInfo);
        };
    }]);

HTML:

<div ng-app="Joy" id="play-ground">
    <form name="userInfo" novalidate ng-controller="FormCtrl">
        <div class="ui input">
            <input ng-model="user.email" ng-message="YOU ARE WRONG" name="User Email" type="email">
        </div>
        <div class="ui input">
            <input ng-model="user.name" name="User Name" type="text" required>
        </div>
        <div class="ui divider"></div>
        <button class="ui primary button" ng-click="submit()">Submit</button>
        <div class="ui positive message">User: {{ user | json }}</div>
    </form>
</div>