繁体   English   中英

Angular 5 Reactive表单:如何在表单控件上动态添加验证器,以及在用户提交表单时显示错误

[英]Angular 5 Reactive form : how to dynamically add validators on a formcontrol, and show errors when a user submits the form

我正在尝试动态设置和删除所需的验证程序 ,如果用户在提交之前单击了该字段,则它似乎可以工作(验证onBlur和onSubmit)。 但是,未经修改的表单提交不会验证控件。

用例 :用户应该能够遍历表单,而不会出现必填字段出现错误的情况。 如果用户输入了一些数据,并且该字段还有其他验证,则应对此进行验证并在模糊时显示错误。 如果用户提交表单时未填写必填字段,则会显示错误。 当用户将注意力集中在该字段上时,错误应消失。 但是,如果用户现在不输入任何内容(空)而退出该字段,则会显示所需的错误。

我有一个Plunker来演示到目前为止的内容。

export class App implements OnInit {
name: string;
myform: FormGroup;
email: FormControl;

constructor() {
  this.name = `Angular! v${VERSION.full}`
}

myform: FormGroup;
email: FormControl;

ngOnInit() {
  this.createFormControls();
  this.createForm();
}

  onSubmit() {
 console.log('sumbitted');
  this.email.setValidators([
    Validators.required,
    specialCharValidator]);
this.email.updateValueAndValidity()
}

createFormControls() {
this.email = new FormControl('', {
  updateOn: 'blur', validators: [
    Validators.required,
    specialCharValidator
  ]
  });
}

  createForm() {
this.myform = new FormGroup({
  email: this.email,
});
}

errorAdd(check) {
if (check.target.checked) {
  this.email.setValidators([
    Validators.required,
    specialCharValidator]);
  console.log('on');
} else {
  console.log('off');
  this.email.setValidators([specialCharValidator]);
  this.email.updateValueAndValidity()
  }
}

}  

看起来该表单正在正确验证,我只是没有使用信息正确显示错误。 更新的插件: https ://plnkr.co/edit/X91VjHmMp1W1LuUdcKy1 ? p = preview

submitted: boolean;
onSubmit() {
this.submitted = true;
}

并在模板中

*ngIf="alphanumeric.errors && ( submitted || alphanumeric.dirty || alphanumeric.touched)">

我不认为您应该动态添加/删除验证器,更好的方法是根据字段的状态(脏/原始/触摸)打开/关闭错误消息。 这样,您可以通过创建自定义规则来控制何时在UI中显示错误。 例如

this.form.get(field).valid && this.form.get(field).touched

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM