如何验证 angular 2 表单

How to validate angular 2 form

Angular 表单验证不 working.Validation 错误消息在 angular 中无法正常工作 2.I 部分执行但未执行 working.Can 你发现我哪里弄错了吗?

https://stackblitz.com/edit/angular2-notifications-example-keedrl?file=app/app.component.ts

脚本:

submitform(){

alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.myform.value));

alert(this.myform.value.gender);

if(this.myform.value.placename)
{ 
 this.placename=false;
}
else{
 this.placename=true; 
}
if(this.myform.value.gender)
{
 this.genders=false;
}
else{
 this.genders=true;
}

if(this.myform.value.minAmount)
{
 this.minAmount=false;
}
else{
 this.minAmount=true;
}
if(this.myform.value.maxAmount)
{
 this.maxAmount=false;
} 
else{
 this.maxAmount=true;
}


  if(!this.myform.valid)
  {
  alert("Form Not valid");
  }
  else
  {
  alert("Form valid");   
  }

  }   

所以你的错误是你手动检查表单值并试图自己验证它们,而不是依赖于你给定的表单值。

我清理了你的代码,并试图删除任何不必要的东西。我对我更改的内容发表了评论。

这是我修改后的结果:

https://stackblitz.com/edit/angular2-notifications-example-nprtlb

这是我更改的详细版本:

  1. 在使用表单检查无效值时,您不需要使用 [{ngModel}]。您可以通过执行 this.myform.controls['placename'].value 之类的操作来访问任何形式的值。所以我删除了你所有的 ngModels,以及所有检查它们是否有效的 if 语句。
  2. 我添加了一个布尔值 formSubmitted,当用户尝试提交表单时它被设置为 true。
  3. 为了在您打开页面时不会立即显示红色文本,我将验证(错误文本)设置为仅在用户尝试提交无效数据后显示。我通过检查表单值是否有效以及用户是否已经尝试提交表单来做到这一点。例如,在您的 html 中:

<p *ngIf="formSubmitted && !myform.controls['placename'].valid" class="error">Please select place name</p>