FormControl始终有效

时间:2018-12-01 18:50:50

标签: angular

我为第一个输入传递了validationType,但是即使我设置了Validators.pattern,无论我输入什么内容,登录表单行组件中的“ onInputBlur”方法都会显示FormControl有效。我真的被困在这里。请帮忙。

login-form.component.html     

  <app-login-form-row
    [label]="'Username'"
    [dataType]="'string'"
    [validationType]="'numeric'"
    (onBlur)="blurMsg(msg)"
  >
  </app-login-form-row>

  <app-login-form-row
    [label]="'Password'"
    [dataType]="'string'">
  </app-login-form-row>

  <button>Submit</button>

</form>

login-form-row.component.ts

import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';

@Component({
  selector: 'app-login-form-row',
  templateUrl: './login-form-row.component.html',
  styleUrls: ['./login-form-row.component.scss']
})
export class LoginFormRowComponent implements OnInit {

  @Input() label: string;
  @Input() dataType: string;
  @Input() validationType: string;
  @Input() required: boolean;

  @Output() onBlur: EventEmitter<string> = new EventEmitter<string>();

  formControl: FormControl;

  constructor() {
  }

  ngOnInit() {
    const validationPattern = this.setValidationPattern();
    console.log('validationPattern', validationPattern);

    this.formControl = new FormControl('', [
      Validators.pattern(validationPattern),
    ]);
  }

  setValidationPattern() {
    let validationPattern = '';
    if (this.validationType === 'alpha') {
      validationPattern = '[a-zA-Z]*';
    }
    if (this.validationType === 'numeric') {
      validationPattern = '[0-9]*';
    }
    if (this.validationType === 'alphanumeric') {
      validationPattern = '[a-zA-Z0-9]*';
    }
    return validationPattern;
  }

  setErrorMessage() {
  }

  onInputBlur(event) {
    // const errorMessage = this.setErrorMessage();
    console.log('is valid?', this.formControl.valid);
    this.onBlur.emit(event.target.value);
  }

}

2 个答案:

答案 0 :(得分:0)

我在stackblitz中尝试过此方法,它似乎可以正常工作-https://stackblitz.com/edit/angular-uuny7c

您可能希望检查如何调用onInputBlur方法,因为如果没有输入值,则验证返回true。您还可以包含HTML吗?

答案 1 :(得分:0)

尝试使用此 onInputBlur 函数运行代码:

     onInputBlur(event) {
      this.formControl.updateValueAndValidity(); // Add this line 
      // const errorMessage = this.setErrorMessage();
      console.log('is valid?', this.formControl.valid);
      this.onBlur.emit(event.target.value);
  }