如何生成错误消息以进行表单验证

时间:2018-10-17 15:19:33

标签: angular6 angular2-forms angular-forms

尝试生成用于表单验证的错误消息,但我不知道如何生成错误消息。我想为错误创建html元素,例如“请通过typescript在输入元素下方动态输入值。

>
  ngOnInit() {
  this.ngForm = this._fb.group({
  name: ['', Validators.required],
  email: ['', Validators.required,Validators.pattern(this.emailPattern)]
   });
  }

1 个答案:

答案 0 :(得分:0)

有一个可以使用的电子邮件验证程序。

ngOnInit() {
  this.ngForm = new FormGroup({
    name: new FormControl('', Validators.required),
    email:  new FormControl('', [Validators.required,Validators.email])
  });
 }

然后在您的html中

<form   [formGroup]="ngForm" (submit)="submitform()">
 <input type="text" class="form-control" name="name" formControlName="name"/>
 <div *ngIf="ngForm.get('name').hasError('required')" style="color:red;">
   Name is required.
 </div>

 <input type="text" class="form-control" name="email" formControlName="email"/>
   <div *ngIf="ngForm.get('email').hasError('required')" style="color:red;">
   Email is required.
 </div>
 <div *ngIf="ngForm.get('email').hasError('email')" style="color:red;">
    Please enter the correct email or valid email.
 </div>

 <button>Submit</button>
</form>
相关问题