为什么我的Reactive表单验证在Angular中失败

时间:2018-08-04 04:41:04

标签: angular validation

我的代码如下:

html

<form [formGroup]="demo2Group">
        <input formControlName="demo2Value">
        <div *ngIf="demo2Value.invalid && (demo2Value.dirty || demo2Value.touched)">
            <div *ngIf="demo2Value.errors.required">
                the value can't be empty
            </div>
            <div *ngIf="demo2Value.errors.minlength">
                the value can't less than 4 length
            </div>
            <div *ngIf="demo2Value.errors.maxLength">
                the value can't more than 6 length
            </div>
        </div>
    </form>

ts

demo2Group;
ngOnInit() {
    this.demo2Group = new FormGroup({
        'demo2Value': new FormControl(null, [
            Validators.required,
            Validators.minLength(4),
            Validators.maxLength(6),
        ])
    });
}
get demo2Value() { return this.demo2Group.get('demo2Value'); }

requiredminlength可以工作,但是maxLength不能工作。如果我使用模板验证,则input元素不能输入超过6个。

但是现在,我可以输入6个以上且没有显示任何错误。

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

DEMO

HTML:

  

maxLength ---->'maxlength'

<h1>
    Reactive Form Validation</h1>

<form [formGroup]="demo2Group">
    <input formControlName="demo2Value">

    <div *ngIf="demo2Group.get('demo2Value').hasError('required') && demo2Group.get('demo2Value').touched">
        the value can't be empty
    </div>
    <div *ngIf="demo2Group.get('demo2Value').hasError('minlength')">
        the value can't less than 4 length
    </div>
    <div *ngIf="demo2Group.get('demo2Value').hasError('maxlength')">
        the value can't more than 6 length
    </div>

</form>

TS:

demo2Group: FormGroup;

  constructor(private fb: FormBuilder) {

  }

  ngOnInit() {
    this.demo2Group = this.fb.group({
      demo2Value: [null, [Validators.required, Validators.minLength(4),
      Validators.maxLength(6),
      ]]
    });

  }