如何验证角度2形式

时间:2018-10-07 18:57:43

标签: angular angular2-forms

Angular表单验证不起作用。验证错误消息在angular 2.中无法正常工作我做了偏见但没有工作。你能找到我做错的地方吗?

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");   
  }

  }   

1 个答案:

答案 0 :(得分:0)

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

我清理了您的代码,并尝试删除了所有不必要的内容。我对我所做的更改发表了评论。

这是我更改的结果:

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>

相关问题