表单验证无法正常工作

时间:2018-12-05 19:50:42

标签: angular

我想为我的Angular-Project添加一些表单验证。 可悲的是,在执行ng serve时遇到以下错误:

  

错误错误:找不到具有未指定名称属性的控件       在_throwError(forms.js:2092)       在setUpControl(forms.js:2000)       在FormGroupDirective.push ../ node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.addControl   (forms.js:4970)       在FormControlName.push ../ node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl   (forms.js:5573)       在FormControlName.push ../ node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges   (forms.js:5492)       在checkAndUpdateDirectiveInline(core.js:20661)       在checkAndUpdateNodeInline(core.js:21929)       在checkAndUpdateNode(core.js:21891)       在debugCheckAndUpdateNode(core.js:22525)       在debugCheckDirectivesFn(core.js:22485)

此外,当我在"test"中用component初始化所有输入字段时,整个表单周围都有一个轮廓(红色轮廓,就像我的{{ 1}}),而不仅限于输入。有人可以跟这个联系吗?

我进行了以下设置:

在我的.component.ts中:

.ng-invalid

我的HTML:

css

1 个答案:

答案 0 :(得分:1)

初始化这些属性:

synchronize

并在模板中使用相同的值进行匹配。

AppComponent.ts

private name: string;
private person: string;
private shortage: string;
private area: string;

模板:

import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  private name: string = 'name';
  private person: string = 'person';
  private shortage: string = 'shortage';
  private id: string = 'id';
  private area: string = 'area';

  private form: FormGroup;
  private formControls = {};

  constructor(
  ) { 
    let validators = [];

    //these three fields are required
    validators.push(Validators.required);
    this.formControls[this.name] = new FormControl(this.name, validators);
    this.formControls[this.id] = new FormControl(this.id, validators);
    this.formControls[this.area] = new FormControl(this.area, validators);
    //these field is required + no special chars are allowed
    validators.push(this.noSpecialChars);
    this.formControls[this.person] = new FormControl(this.person, validators);

    //this field is required + no special chars allowed + length=3
    validators.push(Validators.minLength(3));
    validators.push(Validators.maxLength(3));
    this.formControls[this.shortage] = new FormControl(this.shortage, validators);
    //add formControls to my form
    this.form = new FormGroup (this.formControls);
  }

  ngOnInit() {

  }

  cancelCreation() {
  }

  submit() {
  }
  // dont accept special chars
  noSpecialChars( c: FormControl) {
    let REGEXP = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/);

    return REGEXP.test(c.value) ? {
      validateId: {
        valid: false
      }
    } : null;
  }
}

Stackblitz Demo