如何在角度控制器内添加自定义表单验证?

时间:2015-11-08 19:31:53

标签: javascript angularjs forms validation

我尝试使用angular实现自定义表单验证以进行电子邮件输入。我希望输入只对相应的域有效(这里是@ example.com)。

下面的代码有效,除了它在HTML表单初始化之前运行,触发错误:" TypeError:无法读取属性' $ error'未定义"

app.controller('TeamSignInController', function($scope) {

    $scope.domain = "@example.com";

    var EMAIL_REGEXP = new RegExp("^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+" + $scope.domain + "$", "i");
    $scope.form.$error.required[0].$validators.email = function (modelValue) {
        return EMAIL_REGEXP.test(modelValue);
    }

}

在角度控制器中设置自定义表单验证的最佳方法是什么?只有在表单元素完全加载后才会初始化?我尝试过使用ng-init表单,但在每个表单元素完全加载之前触发。

以下是HTML:

<section id="teamSignIn">
  <form name="form" ng-submit="loginUser(credentials)">
    <div class="form-group">
      <input type="email" class="form-control text-left input-lg" placeholder="you@example.com" ng-model="credentials.email" required>
    </div>
    <div class="form-group">
      <input type="password" class="form-control text-left input-lg" placeholder="password" ng-model="credentials.password" required>
    </div>
    <button class="btn btn-default btn-lg btn-blue" type="submit">
      Sign in
    </button>
  </form>
</section>

0 个答案:

没有答案
相关问题