2016-06-26 43 views
0

我有以下代码进行表单验证。当我在文本框中输入一些值(脏)并且该值无效时,它会显示错误消息。但是,当我不做任何改变(原始)并点击提交时,错误消息不会显示。如何在这种情况下触发错误消息?当原始格式提交时,不会显示错误消息

注意:当我删除原始检查时,甚至在提交之前显示错误消息。

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <!-- bootstrap --> 
 
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> 
 
    <style> 
 
     body{padding-top: 30px;} 
 
    </style> 
 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script> 
 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-resource.js"></script> 
 
    
 
    <script type="text/JavaScript"> 
 

 
     var myApp = angular.module('myApp', []); 
 
     
 
     myApp.controller('myController', function ($scope) { 
 

 
      //Call function on form submit 
 
      $scope.submitForm = function (isValid) { 
 

 
       if (isValid) { 
 
        alert('Valid'); 
 
       } 
 
       else { 
 
        alert('Invalid'); 
 
       } 
 

 
      }; 
 

 
     }); 
 

 
    </script> 
 
</head> 
 
<body ng-app="myApp" ng-controller="myController"> 
 
    <div class="myDiv"> 
 
     <div class="col-sm-8 col-sm-offset-2"> 
 
      <div class="page-header"> 
 
       <h1>Validation</h1> 
 
      </div> 
 
      <form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate> 
 
      <!-- Prevents HTML5 validation using novalidate--> 
 
      
 
      
 
      <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }"> 
 
       <label>Name</label> 
 
       <input type="text" name="name" class="form-control" ng-model="user.name" required> 
 
       <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block"> 
 
        Name required.</p> 
 
      </div> 
 

 
      
 
      <div class="form-group" ng-class="{ 'has-error' : userForm.location.$invalid && !userForm.location.$pristine }"> 
 
       <label>Location</label> 
 
       <input type="text" name="location" class="form-control" ng-model="user.location" 
 
        ng-minlength="3" ng-maxlength="8"> 
 
       <p ng-show="userForm.location.$error.minlength" class="help-block"> 
 
        Location is less than min length.</p> 
 
       <p ng-show="userForm.location.$error.maxlength" class="help-block"> 
 
        Location more than max length.</p> 
 
      </div> 
 

 
      <button type="submit" class="btn btn-primary">Submit</button> 
 
      </form> 
 
     </div> 
 
     
 
    </div> 
 
</body> 
 
</html>

回答

2

尝试使用userForm.$submitted代替$pristine

对于一个良好的学习锻炼和尝试调试鉴于以下

<pre>{{userForm|json}}</pre>