【问题标题】:how to show validation messages when form is submitted in angular js在 Angular js 中提交表单时如何显示验证消息
【发布时间】:2015-07-05 10:08:15
【问题描述】:

我的表单中有几个文本字段和一个电子邮件字段。 我想验证所有字段以进行必需/强制验证。我想验证电子邮件字段以进行电子邮件格式验证。我只想在单击两个按钮并在页面顶部显示验证消息时执行验证。我知道我可以在字段中检查电子邮件和所需的验证,并使用 ng-show 和我可以显示消息的标志。但是我想检查指令中每个字段的值,然后将标志设置为 true,这将使消息出现。

这是我的 HTML。这被加载了为什么主页中的状态提供程序还定义了以下模板和它的控制器。所以它只是一个视图部分:

          <form name="myForm">
             <div ng-show="validationFailed">
               <!-- here i want to display validation messages using cca.validationMsgs object --> 
            </div>   
             <input type="text" name="test" ng-model="cca.field1" require />
             ....
              <input type="email" mg-model="cca.field2" />
             <input type="button" name="mybutton" /> 
          </form>

现在控制器定义在另一个 JS 文件中:

         'use strict';
         (function(){
                 angular.module('store', []);
                 app.controller("StoreController",function(){
                 var cca = this;
                 cca.validationMsgs = {}; 
                 cca.validationFailed = false; //this flag should decide whether validation messages should be displayed on html page or not.when its true they are shown.
                ...//other mapped fields
            });

这里是未完成的指令,我想定义和编写我的逻辑。逻辑将是这样的: 1)迭代所有需要设置的元素并检查它们 $validators 对象 / $error.required 对象已设置 2)如果是,则将validationFailed标志设置为true,将验证消息添加到validationMsgs对象并中断循环。 3) 检查电子邮件类型字段是否设置了 $error.email 对象,如果是 同样将validationFailed标志设置为true并将相应的消息添加到对象。不确定我是否真的需要一个指令。我想在元素内应用指令。

  app.directive("requireOnSubmit",function(){
         var directiveDefinitionObject = {
              restrict:'E',
               //.... need to fill in 
               //I can use link funcion but not sure how to map
               // validationMsgs and validationFailed objects in here.   
          };
         return directiveDefinitionObject;
  });

【问题讨论】:

  • 现在 travelling.so 无法添加代码。但我会解释我的想法是什么。我想迭代表单中的所有元素,如果其中没有值,我想设置一个标志。如果至少一个元素没有值,则此标志将为真。我还将在 ng-show 中使用此标志来显示消息。所以这里有两个问题,如何在模板和指令中绑定标志?这个逻辑应该在点击按钮时执行,以便在哪里附加事件监听器
  • 我添加了一个使用工厂而不是指令的解决方案。看看吧。
  • @Chrillewoodz 我添加了一些代码。我试图解释我想使用指令做什么以及我想在指令中映射的控制器中的字段。我知道你的方式不同。但不确定哪个更好。
  • 指令仅用于 DOM 操作。它不应包含任何有关验证或其他任何内容的逻辑。这在服务或工厂内会更好。我的示例非常详尽地解释了所有内容,您应该能够更改某些变量和名称以使其正常工作。我已经为你的工作奠定了良好的基础,现在由你决定。
  • @Chrillewoodz 好的,让我看看这是否有效,谢谢。如果可行,我会接受它

标签: angularjs validation directive


【解决方案1】:

在没有任何代码或用例的情况下,我将向您展示一种验证输入的通用方法。我将以注册功能为例。

创建一个服务/工厂,它将执行验证并返回一个承诺,如果验证失败,它将reject 承诺。如果没有,它会resolve它。

重要提示:一个promise只能被解决一次(要么被执行要么被拒绝),这意味着resolvereject的第一个声明将始终“获胜”,这意味着您不能覆盖任何resolvereject。因此,在此示例中,如果字段为空并且用户的电子邮件未定义,则错误消息将为All fields must be filled in 而不是Invalid email format

auth.factory('validation', ['$q', function($q) {
  return {
    validateSignup: function(newUser) {

      var q = $q.defer();

      for (var info in newUser) {
        if (newUser[info] === '') {
          q.reject('All fields must be filled in');
        }
      }

      if (newUser.email === undefined) {
        q.reject('Invalid email format');
      }
      else if (newUser.password.length < 8) {
        q.reject('The password is too short');
      }
      else if (newUser.password != newUser.confirmedPass) {
        q.reject('The passwords do not match');
      }

      q.resolve(true);

      return q.promise;
    }
  }
}]);

然后将其注入您的控制器

auth.controller('AuthCtrl', ['$scope', '$location', 'validation', function($scope, $location, validation) {

  $scope.status = {
    message: ''
  }

    // Make sure nothing is undefined or validation will throw error
    $scope.newUser = {
      email: '',
      password: '',
      confirmedPass: ''
    }

    $scope.register = function() {

      // Validation message will be set to status.message
      // This will also clear the message for each request
      $scope.status = {
        message: ''
      }

      validation.validateSignup($scope.newUser)
        .catch(function(err) {

          // The validation didn't go through,
          // display the error to the user
          $scope.status.message = err;
        })
        .then(function(status) {

          // If validation goes through
          if (status === true) {

            // Do something
          }
      });
    }

在 HTML 中你可以有这样的东西:

<form>
  <div>
    <label for="email">Email:</label>
    <input type="email" id="email" ng-model="newUser.email">
  </div>
  <div>
    <label for="password">Password:</label>
    <input type="password" id="confirm-pass" ng-model="newUser.password">
  </div>
  <div>
    <label for="confirm-pass">Confirm password:</label>
    <input type="password" id="confirm-pass" ng-model="newUser.confirmedPass">
  </div>
  <div>
    <div>
      <span ng-bind="status.message"></span>
    </div>
  </div>
  <div>
    <button ng-click="register(newUser)">Register</button>
  </div>
</form>

您可以使用此示例并根据您的用例对其进行修改。

【讨论】:

  • @Chrillwoodz 谢谢。将在几个小时内到家肯定会尝试并会放置一些代码,以便您获得清晰的图片。感谢您在没有任何具体信息的情况下煞费苦心地解释结束
  • @ShaileshVaishampayan 如果您发现它是您问题的可接受答案,请给它投票并接受它作为答案。
  • @Chrillwoodz 你能看看我修改后的问题吗
猜你喜欢
  • 2023-03-12
  • 2017-11-30
  • 1970-01-01
  • 2015-08-04
  • 2016-03-27
  • 2017-11-08
  • 1970-01-01
  • 2019-02-24
  • 1970-01-01
相关资源
最近更新 更多