验证Aurelia中的自定义组件

时间:2015-07-30 01:20:24

标签: aurelia

我正在尝试使用aurelia-validation验证问题的可重用文本框组件。在这种情况下,我需要将我的validate属性与其相对名称绑定。这是我使用组件的视图:

<form role="form" validate.bind="model.validation">
          <text-field name="firstName" value.two-way="model.firstName" label="First Name :" placeholder="Enter first name"></text-field>
          <text-field name="lastName" value.two-way="model.lastName" label="Last Name :" placeholder="Enter last name"></text-field>

查看模型:

import {Validation} from 'aurelia-validation';
import {ClientModel} from '../models/client-model';

export class Registrations{ 

 static inject() { return [Validation]; }

  constructor(validation) {
    this.heading = 'Registrations';
    this.model=new ClientModel('John','Neo','2');
    this.readonly = 'readonly';

    this.model.validation = validation.on(this.model)
    .ensure('firstName')
    .isNotEmpty()
    .hasMinLength(3)
    .hasMaxLength(10)
    .ensure('lastName')
    .isNotEmpty()
    .hasMinLength(5)
    .hasMaxLength(10) ;

  }
activate () {
}

}

文本字段自定义元素视图:

<div class="editor-field">
        <input type="text" value.two-way="value" class="k-textbox" id.one-way="name" placeholder.bind="placeholder" readonly.one-way="readonly" validate="firstName">
    </div>

视图模型:

import {bindable} from 'aurelia-framework';

export class TextField {
    @bindable name = '';
    @bindable value = null;
    @bindable id = '';
    @bindable label = '';
    @bindable placeholder = '';
    @bindable readonly = false;
    @bindable hasValidationError = false;
    @bindable validationMessage = '';
}

它以这种方式工作,但我需要将validate绑定到其正确的名称,所以我尝试了这些方法:

`<input type="text" value.two-way="value" class="k-textbox" id.one-way="name" placeholder.bind="placeholder" readonly.one-way="readonly" validate.bind="name">`

以及字符串插值语法:

<input type="text" value.two-way="value" class="k-textbox" id.one-way="name" placeholder.bind="placeholder" readonly.one-way="readonly" validate="${name}">

但它们不起作用。似乎只接受了一个直接字符串,其中一个字符串位于文本字段自定义元素视图中。如何为每个组件唯一设置验证属性?

1 个答案:

答案 0 :(得分:0)

我认为你在这里遇到了一些问题,所以这样做,看看你怎么做:

1)验证您的顶级vm

this.validation = validation.on(this)
  .ensure('model.firstName')
    .isNotEmpty()
    .hasMinLength(3)
    .hasMaxLength(10)
  .ensure('model.lastName')
    .isNotEmpty()
    .hasMinLength(5)
    .hasMaxLength(10) ;

2)告诉验证框架那些验证来自:

<form role="form" validate.bind="validation">
   <text-field validate="model.firstName" ...></text-field>
   <text-field validate="model.lastName" ...></text-field>

(validate =“model。*”部分可能是不必要的,但也不应该受到伤害)

3)将自定义元素包含在表单组中:

<form role="form" validate.bind="model.validation">
   <div class="form-group">
      <text-field validate="model.firstName" ...></text-field>
   </div>
   <div class="form-group">
      <text-field validate="model.lastName" ...></text-field>
   </div>