我正在應用程序,我有一個窗體,它應該顯示錯誤輸入的輸入字段的驗證錯誤消息。Angular:在提交點擊ng-message驗證
我的表格看起來就像這樣 -
它應該顯示錯誤消息,如果 -
- 輸入欄輸入錯誤修改
- Submit按鈕點擊無修改所需的輸入字段。
它應該顯示如下錯誤信息 -
要做到這一點,我使用NG-消息指令。它會幫助我在$ dirty的輸入字段上顯示錯誤消息。但對於提交按鈕,我找不到正確的方法。目前我正在使用一個將在提交點擊時修改的標誌。但我對一些更好的方法感興趣。是否有預定義的方法來實現這一點?
這裏是我試過的完整例子,這裏是plunkr。
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular-messages.js"></script>
<script>
var app = angular.module('myApp', ['ngMessages']);
app.controller('myCtrl', function($scope) {
$scope.submitForm = function() {
$scope.submitted = true;
if (myForm.$valid) {
alert('Form submitted with passed validation');
}
};
});
</script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<form name="myForm" novalidate ng-submit="submitForm()">
<label>
Enter your name:
<input type="text" name="myName" ng-model="name" ng-minlength="5" ng-maxlength="20" required />
</label>
<div ng-if="submitted || myForm.myName.$dirty" ng-messages="myForm.myName.$error" style="color:red" role="alert">
<div ng-message="required">You did not enter a field</div>
<div ng-message="minlength">Your field is too short</div>
<div ng-message="maxlength">Your field is too long</div>
</div>
<br>
<br>
<label>
Enter your phone number:
<input type="number" name="myPhone" ng-model="phone" ng-maxlength="20" required />
</label>
<div ng-if="submitted || myForm.myPhone.$dirty" ng-messages="myForm.myPhone.$error" style="color:red" role="alert">
<div ng-message="required">You did not enter a field</div>
<div ng-message="maxlength">Your field is too long</div>
</div>
<br>
<br>
<button type="submit">Submit</button>
</form>
</body>
</html>
謝謝!
您可以用'myForm的。$ submitted' – Sravan
你爲什麼不使用角2的形式驗證技術。如果你正在使用angualr 2. https://scotch.io/tutorials/angular-2-form-validation – Harshakj89
@ Harshakj89,他正在使用'angular1.5.0'而不是angular2。 – Sravan