【问题标题】:Angular 5 custom validation display exceptionAngular 5 自定义验证显示异常
【发布时间】:2017-12-24 12:49:25
【问题描述】:

我正在学习 Angular 5 反应式表单,并尝试制作一个示例自定义验证器,该验证器在表单上显示错误消息。当我尝试在项目名称字段(此处称为“namey”)中输入任何内容时,我得到了这个异常(给出的行号只是指向 HTML 中输入的开头):

AppComponent.html:20 ERROR TypeError: Cannot read property 'cannotBeTestx' of null
at Object.eval [as updateDirectives] (AppComponent.html:27)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14338)
at checkAndUpdateView (core.js:13507)
at callViewAction (core.js:13857)
at execComponentViewsAction (core.js:13789)
at checkAndUpdateView (core.js:13513)
at callWithDebugContext (core.js:14739)
at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.js:14276)
at ViewRef_.detectChanges (core.js:11299)
at eval (core.js:5783)

这里是组件代码:

ngOnInit() {
  this.projectForm = new FormGroup({
    namey: new FormControl(null, [Validators.required, this.cannotBeTest1]),
    email: new FormControl(null, [Validators.required, Validators.email]),
    status: new FormControl('1')
  });
}

这是自定义验证器代码:

cannotBeTest1(control: FormControl): {[s: string]: boolean} {
  const name: string = control.value;
  if (name && name.toLowerCase() === 'test') {
    return {'cannotBeTestx': true};
  } else {
    return null;
  }
}

这里是这个元素的 HTML(还有几个其他的表单元素可以正常工作,然后是一个关闭表单标签):

<form class="ui form-vertical" [formGroup]="projectForm" (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label for="project-name">project Name</label>
      <input
        class="form-control"
        type="text"
        id="project-name"
        placeholder="Enter project name"
        formControlName="namey"
      />
      <span class="help-block" *ngIf="projectForm.get('namey').errors['cannotBeTestx'] && (projectForm.get('namey').touched || formSubmitted)">-->
        please enter a valid project name
      </span>
      <span class="help-block" *ngIf="!projectForm.get('namey').valid && (projectForm.get('namey').touched || formSubmitted)">
        please enter a project name
      </span>
    </div>

我一直在弄乱东西,重命名东西并归结为错误显示的这一部分是问题:

projectForm.get('namey').errors['cannotBeTestx']

有趣的是,如果我在 HTML 中删除该错误消息显示,自定义验证器可以正常工作(我无法将项目名称设为“test”),并且我会得到另一个通用错误消息显示。因此,这似乎与我检查该自定义验证器是否无效的方式有关,但我无法终生弄清楚它是什么。

感谢您的帮助!

【问题讨论】:

    标签: angular angular5


    【解决方案1】:

    试试这个

    <span class="help-block" *ngIf="projectForm.controls['namey'].hasError['cannotBeTestx'] && (projectForm.controls['namey'].touched || formSubmitted)">
    
    <span class="help-block" *ngIf="!projectForm.controls['namey'].valid && (projectForm.controls['namey'].touched || formSubmitted)">
    

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-18
      • 1970-01-01
      相关资源
      最近更新 更多