在下面,您将看到我的模板/ HTML表单,但是,验证程序不允许我将输入作为字符串处理?您能解释一下我所缺少的吗?显而易见的文本输入已得到处理和验证,但是我找不到如何处理数字输入类型(例如电话和时间)的示例。我们可以在某处使用toString()javascript方法将其转换为字符串吗? HTML代码示例
<mat-form-field>
<input matInput type="text" formControlName="title" placeholder="Student Name">
<mat-error *ngIf="form.get('title').invalid">Please enter a Student Name.</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput type="tel" formControlName="telephone" placeholder="telephone">
<mat-error *ngIf="form.get(telephone).invalid">Please enter a telephone.</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput type="Time" formControlName="pickUpTime" placeholder="PickUp Time">
<mat-error *ngIf="form.get('pickUpTime').invalid">Please enter a Pickup Time.</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput type="Time" formControlName="dropOffTime" placeholder="DropOff Time">
<mat-error *ngIf="form.get('dropOffTime').invalid">Please enter a Dropoff Time.</mat-error>
</mat-form-field>
Component.ts文件以配置反应形式:
ngOnInit() {
this.form = new FormGroup({
title: new FormControl(null, {
validators: [Validators.required, Validators.minLength(3)]
}),
telephone: new FormControl(null,{
validators: [
Validators.required,
Validators.minLength(5) ]
}),
pickUpTime: new FormControl(null, {
validators: [
Validators.required,
Validators.minLength(5) ]
}),
dropOffTime: new FormControl(null, {
validators: [
Validators.required,
Validators.minLength(5) ]
})
答案 0 :(得分:0)
我认为您没有理由无法处理这些输入。真正的问题是否有必要将它们解析为字符串?我的建议是使这些输入保持其本机类型,以便以后可以使用其功能。也许以下代码示例可以为您提供帮助。
onSubmit(){
if(this.form.valid){
let title: string = this.form.get('title').value;
let telephone: number = this.form.get('title').value;
let pickUpTime: Date = this.form.get('title').value;
let dropOffTime: Date = this.form.get('title').value;
//Do something
}
}