Z
Z
zlodiak2018-03-09 16:40:04
Angular
zlodiak, 2018-03-09 16:40:04

How to add error messages to validation?

I made a reactive form and added custom and built-in validators to it. As a result, in case of an error, the field is surrounded by a red frame. However, at least I want to display a text error message so that the user understands what kind of error has occurred. Please help me to do this.
Here 's a minimal example .
Here is my form component:

currPass: string = '123456';
  form: FormGroup;

  constructor() { }

  ngOnInit() {
    this.form = new FormGroup({
      'currPass':         new FormControl(null, [Validators.required, Validators.minLength(6), Validators.maxLength(10)], this.checkCurrPass.bind(this)),
      'newPass':          new FormControl(null, [Validators.required, Validators.minLength(6), Validators.maxLength(10)])
    });    
  }

  checkCurrPass(control: FormControl): Promise<any> {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if(this.form.value.currPass === this.currPass) {
          resolve(null);
        } else {
          resolve({checkCurrPass: true});
        } 
      });     
    });
  }

  onSubmit(): void {
    console.log('submit', this.form);
  }

Here is the template:
<form class="form" [formGroup]="form" (ngSubmit)="onSubmit()">
    <div class="line" [ngClass]="{'error': !form.controls.currPass.valid && form.controls.currPass.dirty}">
      <label for="">Текущий пароль</label>
      <input type="text" formControlName="currPass">
    </div>

    <div class="line" [ngClass]="{'error': !form.controls.newPass.valid && form.controls.newPass.dirty}">
      <label for="">Новый пароль</label>
      <input type="password" formControlName="newPass">
    </div>

    <div class="line">
      <button [disabled]="!form.valid" type="submit">Отправить</button>
    </div>

    <div class="look" (click)="look()">look</div>
  </form>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-03-09
@zlodiak

Well, so , for example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question