【发布时间】:2018-06-27 04:46:09
【问题描述】:
我正在研究 Angular 2 反应式表单。我在使用 Validators.pattern() 进行表单字段验证时遇到问题。一旦我开始在输入字段中输入,就会得到异常Cannot read property 'subscribe' of null。
打字稿代码
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(),
])
});
}
'name' 属性根据模式进行验证。
HTML 代码
<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>
正在尝试验证输入字段名称。
例外Cannot read property 'subscribe' of null
当我从 name 属性中删除 Validators.pattern() 时,它工作正常。我无法理解为什么它在这里失败,因为我已经以相同的形式将 Validators.pattern() 用于其他属性并且它对它们很好。
【问题讨论】:
-
我觉得应该是
[ '', Validators.compose([Validators.required, Validators.pattern(/^[a-zA-Z0-9]+$/)])] -
知道了。 @swaroop 强调了我正在做的错误。感谢您的帮助
标签: validation typescript angular2-forms