我在anuglar2中做出反應。當試圖提交我的表格時,表格說明它是無效的。我知道是什麼導致了這個問題,但不知道如何解決這個問題。對於我的表單控件之一,我創建了一個自定義驗證器來檢查它是否是一個數字。所以它是必需的,它必須是一個數字。如果我在表單上刪除了我的自定義驗證,它就會恢復正常。我如何解決這個問題,這樣我可以保留我的自定義驗證?Angular2 - 表單無效
contact.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { ValidationService } from './validation.service'
@Component({
selector:'contact',
providers:[ValidationService],
templateUrl:'./contact.component.html'
})
export class ContactComponent {
public TicketForm = null ;
projects:Array<string> = ['Project One','Project Two','Project Three'];
constructor(public fb: FormBuilder) {
this.TicketForm = fb.group({
name: [null, Validators.required],
email: [null, Validators.required],
phone: [null, Validators.required],
ticketID: [null, Validators.compose([Validators.required, ValidationService.numberValidation])],
});
}
submit(form:any, isValid:boolean) {
console.log(form, isValid);
}
}
Validation.service.ts
import { Injectable } from '@angular/core';
import { AbstractControl } from "@angular/forms";
interface ValidationResult {
[key:string]:boolean;
}
@Injectable()
export class ValidationService {
constructor() {}
public static numberValidation(control:AbstractControl): ValidationResult {
return ({'valid':!isNaN(control.value)});
}
}
驗證器應該返回'null',如果控件有效,請按照https://angular.io/docs/ts/latest/cookbook/form-validation.html – jonrsharpe