如何在角度js

时间:2015-07-05 10:08:15

标签: angularjs validation directive

我的表单中有几个文本字段和一个电子邮件字段。 我想验证所有字段的必需/强制验证。我想验证电子邮件字段以验证电子邮件格式。我只想在点击两个按钮并在页面顶部显示验证消息时才进行验证。我知道我可以在现场检查电子邮件和所需的验证,并使用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;
  });

1 个答案:

答案 0 :(得分:1)

没有任何代码或用例,我只会向您展示验证输入的通用方法。我将使用注册功能作为示例。

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

重要说明:承诺只能解决一次(要么已履行或被拒绝),这意味着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>

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