![](/img/trans.png)
[英]AngularJS form validation: show error message for checkbox after click on submit
[英]Error message show before the form submit in angularjs form validation
我使用angularjs進行了表單驗證。 但我遇到的問題是頁面加載時顯示的錯誤消息。 但是這個消息會在收到錯誤后顯示出來。 只是我想要使用指令設置驗證摘要的余數。 我能做什么?
我的代碼如下:
<label>UserName</label>
<input type="text" class="form-control" name="UserName" ng-model="userVM.UserName" required ng-minlength="8" ng-maxlength="20" />
<div validation-message ng-show="customerForm.UserName.$error.required" class="error">
Username is required
</div>
指令如下
NusPayApp.directive("validationSummary", function () {
return {
restrict: "A",
require: "^form",
template: "<div class='alert alert-warning'><a class='close' ng-click='toggleValidationSummary()'>×</a><h4 class='alert-heading'>Warning!</h4><li ng-repeat='(expression,message) in validationMessages'>{{message}}</li></ul></div>",
link: function (scope, element, attributes, controller) {
scope.validationMessages = {};
// Hooks up a watch using [ng-show] expression
controller.watchValidation = function (expression, message) {
// watch the return value from the scope.$eval(expression)
scope.$watch(function () { return scope.$eval(expression); }, function (isVisible) {
// check if the validation message exists
var containsMessage = scope.validationMessages.hasOwnProperty(expression);
// if the validation message doesn't exist and it should be visible, add it to the list
if (!containsMessage && isVisible) {
scope.validationMessages[expression] = message;
}
// if the validation message does exist and it shouldn't be visible, delete it
if (containsMessage && !isVisible) {
delete scope.validationMessages[expression];
}
});
};
}
};
});
讓我幫忙給我一些建議。 我需要確保在表單提交后顯示錯誤消息。
您可以在范圍中添加新變量以檢查表單是否已提交。
$scope.isFormSubmit = false
然后,如果您的表單有錯誤,則將此標志更新為true
if($scope.form.$valid)
{
//Submit your form
$scope.isFormSubmit = false
}
else
{
$scope.isFormSubmit = true
}
將您的HTML代碼更新為
<div validation-message ng-show="customerForm.UserName.$error.required && isFormSubmit" class="error">
Username is required
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.