如何使用aurelia-validate和对象属性进行验证?

时间:2015-05-28 23:20:21

标签: decorator ecmascript-6 aurelia aurelia-validation

我使用aurelia-validate,如果我使用变量,我的验证工作正常,但我需要它来验证对象的属性而不是变量:

以下是有效的:

  import {Validation} from 'aurelia-validation';
  import {ensure} from 'aurelia-validation';
  import {ItemService} from './service';

  export class EditItem {
    static inject() {
      return [Validation, ItemService];
    }

    @ensure(function(it){
      it.isNotEmpty()
        .hasLengthBetween(3,10);
    })
      name = '';

    @ensure(function(it){
      it.isNotEmpty()
        .hasMinLength(10)
        .matches(/^https?:\/\/.{3,}$/) //looks like a url
        .matches(/^\S*$/); //no spaces
    })
      url = '';

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

    activate(params){
      return this.service.getItem(params.id).then(res => {
        console.log(res);
        this.name = res.content.name; //populate
        this.url = res.content.url;
      });
    }

    update() {
      this.validation.validate().then(
        () => {
          var data = {
            name: this.name,
            url: this.url
          };

          this.service.updateItem(data).then(res => {
            this.message = "Thank you!";
          })
        }
      );
    }
  }

这是我尝试做的事情(但是没有工作)......我也不确定保持房产的性能是否更好class或者有一个名为this.item的属性,它包含属性(这是典型的角度方式):

  import {Validation} from 'aurelia-validation';
  import {ensure} from 'aurelia-validation';
  import {ItemService} from './service';

  export class EditItem {
    static inject() {
      return [Validation, ItemService];
    }

    @ensure(function(it){
      it.isNotEmpty()
        .hasLengthBetween(3,10);
    })
      this.item.name; //no assignment here should happen 

    @ensure(function(it){
      it.isNotEmpty()
        .hasMinLength(10)
        .matches(/^https?:\/\/.{3,}$/) //looks like a url
        .matches(/^\S*$/); //no spaces
    })
      this.item.url; //no assignment?

    constructor(validation, service) {
      this.validation = validation.on(this);
      this.service = service;
      this.item = null;
    }

    activate(params){
      return this.service.getItem(params.id).then(res => {
        console.log(res);
        this.item = res.content; //populate with object from api call
      });
    }

    update() {
      this.validation.validate().then(
        () => {
          var data = {
            name: this.item.name,
            url: this.item.url
          };

          this.service.updateItem(data).then(res => {
            this.message = "Thank you!";
          })
        }
      );
    }
  }

有人可以在这里给我一些关于如何对现有对象使用验证器的指导(对于编辑页面)吗?

2 个答案:

答案 0 :(得分:4)

验证适用于各种情况,但使用@ensure装饰器只能用于在简单属性上声明规则(就像你发现的那样)。

...因此

选项a:使用流畅的API'ensure'方法替换ensure装饰器,这支持'嵌套'或'复杂'绑定路径,例如:

import {Validation} from 'aurelia-validation';
import {ItemService} from './service';

export class EditItem {
static inject() {
  return [Validation, ItemService];
}

constructor(validation, service) {
  this.validation = validation.on(this)
    .ensure('item.url')
      .isNotEmpty()
      .hasMinLength(10)
      .matches(/^https?:\/\/.{3,}$/) //looks like a url
      .matches(/^\S*$/)
    .ensure('item.name')
      .isNotEmpty()
      .hasLengthBetween(3,10);
  this.service = service;
  this.item = null;
}

activate(params){
  return this.service.getItem(params.id).then(res => {
    console.log(res);
    this.item = res.content; //populate with object from api call
  });
}

update() {
  this.validation.validate().then(
    () => {
      var data = {
        name: this.item.name,
        url: this.item.url
      };

      this.service.updateItem(data).then(res => {
        this.message = "Thank you!";
      })
    }
  );
}

}

注意:您甚至可以在设置项目之前设置验证。很酷,没有?

选项b:由于验证规则是特定于项目的,因此您可以使用该类中的@ensure装饰器将验证规则移到项目类中。 然后,您可以在检索项目后在VM中设置验证:this.validation = validation.on(this.item);或者,您的服务可以在将项目返回到VM并将其作为模型的固有部分时设置验证:{ {1}}

选项a最简单,似乎符合您的经验。选项b更易于维护,因为模型的验证规则将存在于模型上,而不是视图模型上。但是,如果您选择选项b,you might have to adjust your HTML a bit to make sure validation hints appear

答案 1 :(得分:1)

使用验证器的.on方法将规则应用于对象属性。

在检索名为stock的对象后调用以下示例,它验证数量不为空且仅为数字。希望这会有所帮助...

let stock = {
  name: 'some name'
  minimumQuantity: '1'
};

applyRules() {
  ValidationRules
    .ensure((m: EditStock) => m.minimumQuantity)
    .displayName("Minimum Quantity")
    .required()
    .withMessage(`\${$displayName} cannot be blank.`)
    .matches( /^[0-9]*$/)
    .withMessage(`\${$displayName} must be numeric only.`)       

  .on(this.stock);
}