简体   繁体   中英

Error message show before the form submit in angularjs form validation

I've made form validation using angularjs. But I am facing a problem Which is error message shown at the page load. But this message will show after getting error. Just I want to remainder that I have set validation summary using directive. What can I do?

My code is as bellow

<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>

Directive is as bellow

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];
                    }
                });
            };
        }
    };
});

Let me help to give me suggestion. I need to make sure error message will show after form submit.

You can add new Variable in scope to check if form is submitted.

$scope.isFormSubmit = false

Then if your form has errors then update this flag to true

if($scope.form.$valid)
{
      //Submit your form
      $scope.isFormSubmit = false
}
else
{
     $scope.isFormSubmit = true
}

Update your HTML Code to

<div validation-message ng-show="customerForm.UserName.$error.required && isFormSubmit" class="error">
 Username is required
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM