2017-04-26 62 views
2

我遇到了在HTML中呈現錯誤的問題。Aurelia在輸入時顯示驗證錯誤

視圖模型:

import {autoinject} from 'aurelia-framework'; 
import { ValidationRules, ValidationController, ValidationControllerFactory } from 'aurelia-validation'; 

// Models 
import { NewCustomer } from '../../models/customer'; 

@autoinject 
export class Register { 
    controller: ValidationController; 
    customer: NewCustomer; 

    constructor(controllerFactory: ValidationControllerFactory, customer: NewCustomer) { 
     this.controller = controllerFactory.createForCurrentScope(); 
     this.customer = customer; 
     this.controller.addObject(this.customer); 
    } 

    validate(): void { 
     this.controller.validate().then(res => { 
      console.log(res); 
      if(res.valid) { 
       this.register(); 
      } 
     }); 
    } 
} 

ValidationRules 
    .ensure((c: NewCustomer) => c.first_name).displayName('first name').required().withMessage(`\${$displayName} cannot be blank.`) 
    .ensure((c: NewCustomer) => c.last_name).displayName('last name').required().withMessage(`\${$displayName} cannot be blank.`) 
    .ensure((c: NewCustomer) => c.email).displayName('first name').email().required().withMessage(`\${$displayName} cannot be blank.`) 
    .ensure((c: NewCustomer) => c.phone_number).displayName('phone number').matches(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/).withMessageKey('invalid phone number').required().withMessage(`\${$displayName} cannot be blank.`) 
    .ensure((c: NewCustomer) => c.password).displayName('password').minLength(7).required().withMessage(`\${$displayName} cannot be blank.`) 
    .on(NewCustomer); 

而且與例如輸入:

<div class="sb-input-group no-margin" validation-errors.bind="first_nameErrors"> 
     <label>First Name</label> 
     <input value.bind="customer.first_name" placeholder="First Name" class="sb-input-control"> 
     <span class="help-block danger" repeat.for="errorInfo of first_nameErrors"> 
      ${errorInfo.error.message} 
     <span> 
    </div> 

現在,每當我提交表單,我檢查我看到驗證規則被拾起正確的控制檯;但是它們不在視圖中呈現。我也試過validation-errors.bind="customer.first_nameErrors",也沒有工作。我將錯誤綁定到視圖的正確格式是什麼?

編輯:這裏是NewCustomer對象

export class NewCustomer { 
    first_name: string; 
    last_name: string; 
    email: string; 
    phone_number: string; 
    password: string; 
    companies: Company[]; 
    selected_company_id: string; 
} 

回答

2

它看起來像你缺少「&驗證」標記HTML中使用您的驗證控制器註冊綁定實例。

還簽出一個驗證渲染器(有一些Bootstrap Validation Renderers左右),它可以幫助您無處不在地添加錯誤跨度。

大部分是在the docs,但是我花了很多通行證來理解這一切!