2015-03-02 85 views
0

如何通過單擊按鈕驗證我的表單。用戶在字段中鍵入時必須禁用驗證,並且只有在單擊按鈕時才必須啓用驗證。我怎樣才能做到這一點?如何在AngularJs中單擊按鈕時顯示錯誤類?

var app = angular.module("App",[]); 
 

 
app.controller("Controller", function($scope){ 
 
    
 
    $scope.Validate = function(){ 
 
    if($scope.frm.$invalid){ 
 
     alert("Form is invalid"); 
 
    } 
 
    else{ 
 
     alert("Form is valid"); 
 
    } 
 
    }; 
 
    
 
});
input.ng-invalid:not(.has-focus) { 
 
    border:1px solid #ff7f7f; 
 
    background-color: #ffeeee; 
 
}
<html ng-app="App"> 
 
<head> 
 
<script src="//code.jquery.com/jquery.min.js"></script> 
 
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" /> 
 
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script> 
 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script> 
 
    <meta charset="utf-8"> 
 
    <title>JS Bin</title> 
 
</head> 
 
<body> 
 

 
    <div ng-controller="Controller"> 
 
    
 
    <form name="frm"> 
 
     
 
     <input type="text" ng-model="user.name" required/> 
 
     
 
     <input type="email" ng-model="user.email" required> 
 
     
 
    </form> 
 
    
 
    <a class="btn btn-info" ng-click="Validate()">Validate! </a> 
 
    </div> 
 
    
 
    
 
</body> 
 
</html>

回答

0

required標籤是從HTML5 /瀏覽器驗證,是不是好習慣使用它們,將所有的驗證,以angularjs

因此,禁用所有的瀏覽器驗證(使用novalidate標籤)

<form name="frm" novalidate> 

    <input type="text" ng-model="user.name" /> 

    <input type="email" ng-model="user.email" /> 

</form> 
<a class="btn btn-info" ng-click="Validate()">Validate! </a> 
0

我爲所有可能的最簡單的答案。爲什麼不直接隱藏驗證按鈕,直到你希望他們看到它?

那麼在所有字段都有信息之前,ng-hide如何,然後一旦滿足這些條件就會發生ng-show。那麼你可以做ng-click語句來驗證表單嗎?

+0

我無法隱藏按鈕。因爲我們接受的線框包含啓用「下一步按鈕」。當用戶點擊「下一步按鈕」驗證將起作用。這個問題只能通過指令來實現嗎? – 2015-03-03 06:41:50

+0

您可能想要創建自定義指令。我有點困惑於「這個問題可能只與指令有關嗎?」 – James 2015-03-03 17:19:13

相關問題