2016-11-24 96 views
0

我需要驗證文本框。我正在使用ng-required =「true」,但它沒有顯示所需的消息。如果我點擊保存按鈕,它直接放置保存()功能。如何避免它。如何驗證AngularJS中的文本框

<div ng-app="LearnApp" ng-controller="csrControl"> 
    <table> 
     <tr> 
      <td> 
       Name 
      </td> 
      <td> 
       : 
      </td> 
      <td> 
       <input id="txtName" type="text" ng-model="txtName" ng-required="true" placeholder="Name" /> 
      </td> 
     </tr> 
     <tr> 
      <td> 
       Address 
      </td> 
      <td> 
       : 
      </td> 
      <td> 
       <input id="txtAddress" type="text" ng-model="txtAddress" ng-required="true" placeholder="Address" /> 
      </td> 
     </tr> 
     <tr> 
      <td colspan="3" align="right"> 
       <input id="btnSave" type="button" value="Save" class="button" ng-click="save()" /> 
       <input id="btnCancel" type="button" value="Cancel" class="button" /> 
      </td> 
     </tr> 
    </table> 
</div> 
<script type="text/javascript"> 
    var app = angular.module("LearnApp", []); 
    app.controller("csrControl", function ($scope, $http) { 

     $scope.save = function() { 

     }; 

    }); 
</script> 
+0

與嘗試,它只是「必要」,不NG-所需=「真」 – rrd

+0

請檢查angularjs –

+0

哪條消息,你希望看到的表單驗證?我沒有看到任何包含(錯誤)消息的html。或者你只是想觸發html5驗證? – devqon

回答

0

我想你錯過了Form標籤。

<form name="myForm" > 
    .... 
</form> 
0

你需要添加表單標籤,並給名稱形式。而且用這個名字像錯誤消息:

<form name="myForm" novalidate> 

    //some code 

    <input type="text" ng-model="abc" name="txt1" ng-required="true"/> 
     <div ng-messages="myForm.txt1.$error"> 
      <div ng-message="required"> This is Required! </div>          
     </div> 
</form> 

而且還穿上了服務器端的條件來驗證表格之前保存:

$scope.Save = function() { 
      if ($scope.myForm.$valid) { 

      //perform save 

      } 
    }; 
0

使用形式標籤和NG提交它將調用提供的函數,如果您的表單有效或拋出默認的html5驗證錯誤。僅使用「必需的」屬性將使輸入成爲必需。如果必須評估可以分配給ng-required指令的表達式,則使用ng-required。

如果您想要特定類型的錯誤消息並避免默認的html5驗證,您可以在表單標記中使用novalidate指令。 有關Angular表單驗證的更多信息,官方documentation和此tutorial將有所幫助。

檢查下面的代碼更改。

<form ng-submit="save()"> 
    <table> 
    <tr> 
     <td> 
      Name 
     </td> 
     <td> 
      : 
     </td> 
     <td> 
      <input id="txtName" type="text" ng-model="txtName" required placeholder="Name" /> 
     </td> 
    </tr> 
    <tr> 
     <td colspan="3" align="right"> 
      <input id="btnSave" type="submit" value="Save" class="button"/> 
      <input id="btnCancel" type="button" value="Cancel" class="button" /> 
     </td> 
    </tr> 
</form>