使用ember.js进行电子邮件验证

时间:2016-09-12 13:19:56

标签: javascript forms validation ember.js

如果数据库中存在电子邮件,我想在我的Ember JS应用程序测试中设置验证表单。

问题是我无法直接从formValidators致电我的商店。

formValidators: {
email: [
  {
    message: 'Please provide email in a valid format',
    validate: (inputValue) => {
      let emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
      return emailPattern.test(inputValue);
    }
  },
  {
    message: 'Email already exist',
    validate: (inputValue, self) => {
      return this.get('store').queryRecord('email',
        {
          filter: {
            email: inputValue
          }
        }).then(function () { return false })
    }
  }
]}

在chrome控制台中运行时出现此错误:

 TypeError: _this2.get is not a function(…)

我想这很容易出问题,但我花了几个小时而不知道如何解决这个问题。

2 个答案:

答案 0 :(得分:0)

_this2是Babel在编译代码时创建的变量。

Babel通常使用箭头函数执行此操作,因此它可以模拟其维护与其外部作用域相同的上下文的行为。

例如,此代码:

this.getStuff().then(() => {
  this.getMoreStuff();
});

会转变为:

var _then1 = this;
this.getStuff().then(function() {
  _then1.getMoreStuff(); // <-- Use a variable to maintain scope
});

箭头函数的这种行为意味着,即使用作方法,它仍然会this指向定义它的外部范围。

示例:

var x = {
  m: () => {
    console.log(this === x); // `this` is not x, its global
  }
}

x.m(); // false

尝试将您的电子邮件验证方法声明为正常功能,这样可以解决您的问题:

validate: function(inputValue, self) {
  // ...

甚至用方法简写:

validate(inputValue, self) {
  // ...

原因如下:

var x = {
  m() {
    console.log(this === x); // `this` is x
  }
}

x.m(); // true

答案 1 :(得分:0)

好的,我设置了一个动作:

validate(inputValue) {
      this.get('store').queryRecord('buyer',
        {
          filter: {
            email: inputValue
          }
        }).then(function (inputValue) {
          console.log(inputValue)
        });
}

并输入onChange action:

 onChange=(action "validate" validEmail)

但还有另一个错误:

Assertion Failed: You must include an 'id' for buyer in an object passed to 'push'
相关问题