【问题标题】:Error message show before the form submit in angularjs form validation在 angularjs 表单验证中提交表单之前显示错误消息
【发布时间】:2014-06-12 10:33:46
【问题描述】:

我已经使用 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];
                    }
                });
            };
        }
    };
});

让我帮忙给我建议。我需要确保表单提交后会显示错误消息。

【问题讨论】:

    标签: javascript angularjs validation


    【解决方案1】:

    您可以在范围内添加新变量以检查表单是否已提交。

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

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 2019-02-28
      • 2014-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多