我有一个表单,我成功加载了来自fetch的数据。如果我然后单击该表单上的保存,Aurelia验证将评估那些数据为空的表单文本字段,并将其显示为保存按钮下方的错误 - 下图。
验证在空表单上完美运行,但是对于带有加载值的表单,就好像表单表现得像空一样。
当然,如果文本框中有字符,可以通过键入或从提取中加载,它应该在“required”的上下文中评估它并传递?
目前它不是从fetch加载的。
代码
这是打字稿视图模型:
import { HttpClient } from "aurelia-fetch-client";
import { autoinject, inject, NewInstance, PLATFORM } from "aurelia-framework";
import { Router, activationStrategy } from "aurelia-router";
import {
ValidationControllerFactory,
ValidationController,
ValidationRules,
validateTrigger
} from "aurelia-validation";
import { BootstrapFormRenderer } from "../../../../services/bootstrapFormRenderer/bootstrapFormRenderer";
//import from '../../../../services/customValidationRules/customValidationRules'
import { AuthService } from "../../../../services/auth/auth-service"
@autoinject
export class Client {
controller: ValidationController;
client = new ClientDetails;
job: Job;
visits = Array();
hasClientId: boolean;
heading: string = "New Client";
headingIcon: string = "fa-user-plus";
username: string;
constructor(
private authService: AuthService,
private router: Router,
private controllerFactory: ValidationControllerFactory
) {
this.router = router;
this.controller = controllerFactory.createForCurrentScope();
this.controller.addRenderer(new BootstrapFormRenderer());
this.controller.addObject(this)
this.controller.addObject(this.client);
}
// Required to reload new instance.
determineActivationStrategy() {
return activationStrategy.replace; //replace the viewmodel with a new instance
// or activationStrategy.invokeLifecycle to invoke router lifecycle methods on the existing VM
// or activationStrategy.noChange to explicitly use the default behavior
}
activate(parms, routeConfig) {
this.hasClientId = parms.id;
if (this.hasClientId) {
const headers = this.authService.header();
fetch("/api/Client/edit/" + parms.id, {
method: "GET",
headers
})
.then(response => response.json())
.then(data => {
this.client = data
})
this.heading = "Edit Client"; // An id was submitted in the route so we change the heading as well.
this.headingIcon = "fa-pencil-square-o";
}
return null;
}
submitClient() {
console.log("gets Here");
console.log("this.controller.validate(): ", this.controller.validate());
//this.controller.validate();
if (this.controller.validate()) {
console.log("Hi!");
}
}
rowSelected(jobId: number) {
let job = this.client.jobs.filter(f => f.id === jobId);
if (job && job.length > 0) {
var jobVisits = job.map(j => { return j.jobVisits; })[0];
this.visits = jobVisits;
}
}
}
export class ClientDetails {
clientId: number;
clientNo: number;
company: boolean;
companyName: string;
abn: string;
isWarrantyCompany: boolean;
requiresPartsPayment: boolean;
clientFirstName: string;
clientLastName: string;
email: string;
mobilePhone: string;
phone: string;
notes: string;
address: AddressDetails;
jobs: Job[];
bankName: string;
bankBSB: string;
bankAccount: string;
active: boolean;
deActivated: string;
activity: boolean;
dateCreated: string;
dateUpdated: string;
creatorId: number;
creatorName: string;
}
class Job {
id: number;
agentJobNo: number;
jobNo: number;
jobType: string;
jobVisits: Visit[]
numberOfVisits: number;
status: string;
}
class Visit {
jobVisitId: number;
dateCreated: string;
visitDate: string;
startTime: string;
endTime: string;
}
class AddressDetails {
address1: string;
address2: string;
suburb: string;
postcode: string;
stateShortName: string;
addressLocationId: number;
}
// Validation Rules.
ValidationRules
.ensure((a: ClientDetails) => a.companyName).required()
.when((a: ClientDetails) => a.company === true)
.withMessage('Company name is required if client is a company.')
.ensure((a: ClientDetails) => a.clientLastName).required()
.ensure((a: ClientDetails) => a.mobilePhone).required()
.on(ClientDetails)
fetch在activate函数中,只有在提供了id时才会获取。 fetch使用返回的数据加载“client”。这有效,我有一个表单,其中显示了获取的所有数据。
但是,如果单击“保存”按钮,即使两个字段“lastName”和“mobilePhone”中包含值,“submitClient()”函数也会触发,“this.controller.validate()”会评估这些字段是空的。
难道它看不到这些字段中有值吗?我在这里缺少什么吗?
以下是视图的“lastName” - 请注意“& validate”存在。
<div class="col-md-6">
<div class="col-md-3">
<div class="form-group">
<label class="control-label pull-right" for="lastname">Last Name: </label>
</div>
</div>
<div class="col-md-9">
<div class="form-group">
<input type="text" value.bind="client.clientLastName & validate" class="form-control" id="lastname" placeholder="Last Name...">
</div>
</div>
</div>
答案 0 :(得分:1)
从服务器加载现有客户端时,您将this.client
属性设置为简单的JSON对象。它将不再是ClientDetails
的实例,因此验证规则不起作用,因为它们仅适用于ClientDetails
个实例。
您需要创建ClientDetails
的新实例,并从data
返回的fetch
对象中填充它。它可以手动创建一个构造函数或在映射方法来进行ClientDetails
,接受数据对象和映射到每个ClientDetails
属性(this.clientId = data.clientId
,等)。
作为替代方案,您可以使用某种通用映射器函数来执行属性名称的映射。我对TypeScript不太熟悉,但this SO question有很多关于如何做到这一点的解决方案。