I have implemented form validation using angularjs, but I am encountering an issue where the error message is displayed upon page load instead of after an actual error. I have set up a validation summary using a directive. Can you please advise me on how to resolve this?
Below is my code:
<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>
The directive is defined as follows:
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 = {};
// Watches for changes in the expression and message
controller.watchValidation = function (expression, message) {
scope.$watch(function () { return scope.$eval(expression); }, function (isVisible) {
var containsMessage = scope.validationMessages.hasOwnProperty(expression);
if (!containsMessage && isVisible) {
scope.validationMessages[expression] = message;
}
if (containsMessage && !isVisible) {
delete scope.validationMessages[expression];
}
});
};
}
};
});
Please provide suggestions on ensuring that the error messages are shown only after the form is submitted.