集中 Aurelia 验证逻辑

Centralize Aurelia validation logic

我想在@ensure 中集中验证逻辑,但我不知道该怎么做。 这是文档中的示例:

import {Validation} from 'aurelia-validation';
import {ensure} from 'aurelia-validation';

export class Person {
  static inject() { return [Validation];}
  
  //I want to inject validation logic here instead of using function(it){...}
  @ensure(function(it){ it.isNotEmpty().hasLengthBetween(3,10) })
    firstName = 'John';

  constructor(validation) {
    this.validation = validation.on(this);
  }
}

我想将上面的代码更改为如下所示:

import {Validation} from 'aurelia-validation';
import {ensure} from 'aurelia-validation';
import {UserValidation} from 'user/userValidation'; //custom validation logic here

export class Person {
  static inject() { return [Validation];}
  
  //can I do something like this instead of using function(it){...}?
  @ensure(UserValidation.firstName)
    firstName = 'John';

  constructor(validation) {
    this.validation = validation.on(this);
  }
}

如果我们只需要在一个页面上收集名字,那么我们根本不需要这样做,但是由于我们可能需要让用户在多个不同的页面上输入他们的名字,所以我们希望集中某处的验证逻辑,这样我们就不必将其复制并粘贴到任何地方。我们也不想创建 "first name component" 因为 UI 在每个页面上都会不同,所以我们只想重用验证逻辑。

更新: 我在 Aurelia 讨论中问了这个问题,并被要求尝试以下操作。

//userValidation.js
export function firstName(it){ it.isNotEmpty().hasLengthBetween(3,10)};

import {Validation} from 'aurelia-validation';
import {ensure} from 'aurelia-validation';
import * as userValidation from 'user/userValidation';

export class Person {
  static inject() { return [Validation];}
  
  @ensure(userValidation.firstName)
    firstName = 'John';

  constructor(validation) {
    this.validation = validation.on(this);
  }
}

但我收到此错误:未处理的承诺拒绝错误:实例化人员时出错。知道我该如何解决这个问题吗?

实际上,以下代码有效!

//userValidation.js
export function firstName(it){ it.isNotEmpty().hasLengthBetween(3,10)};

//person.js
import {Validation} from 'aurelia-validation';
import {ensure} from 'aurelia-validation';
import * as userValidation from 'user/userValidation';

export class Person {
  static inject() { return [Validation];}
  
  @ensure(userValidation.firstName)
    firstName = 'John';

  constructor(validation) {
    this.validation = validation.on(this);
  }
}