我正在研究Angular 2反应形式。我使用Validators.pattern()在表单字段验证中遇到问题。一旦我开始输入输入字段,就会得到异常Cannot read property 'subscribe' of null
。
TYPSCRIPT CODE
createForm(){
this.jobForm = this.fb.group({
name: ['', Validators.required, Validators.pattern(/^[a-zA-Z0-9]+$/)],
epType: ['ENDPOINT_TYPE_SBC', Validators.required],
streams : this.fb.array([
this.createStreamControls(),
]),
channels:this.fb.array([
this.createChannelControls(),
])
});
}
以'名称'属性根据模式进行验证。
HTML CODE
<div class="ui-grid-col-8 ">
<input id="name" formControlName="name" pInputText class="width-60" />
<br>
<small *ngIf="jobForm.controls.name.hasError('required') && jobForm.controls.name.touched" class="text-danger">Required</small>
<small *ngIf="jobForm.controls.name.hasError('pattern') && jobForm.controls.name.touched" class="text-danger">Should be alpha-numeric without space</small>
</div>
尝试验证输入字段名称。
EXCEPTION Cannot read property 'subscribe' of null
当我从name属性中删除Validators.pattern()时,它可以正常工作。我无法理解为什么它在这里失败,因为我已经使用相同形式的Validators.pattern()用于其他属性,并且它适用于它们。
答案 0 :(得分:1)
需要在表单组的第二个参数中传递Validators数组。
createForm(){
this.jobForm = this.fb.group({
name: ['', [Validators.required, Validators.pattern(/^[a-zA-Z0-9]+$/)]],
epType: ['ENDPOINT_TYPE_SBC', [Validators.required]],
streams : this.fb.array([
this.createStreamControls(),
]),
channels:this.fb.array([
this.createChannelControls(),
])
});
}