如何检查为什么我的自定义验证器不起作用?

时间:2019-12-08 13:13:06

标签: angular forms validation

所以我试图创建一个角度反应式表单,该表单的ID输入字段必须是唯一的(在某种意义上,如果提交的ID已经存在,则应该在html正面弹出一个错误)。 其背后的逻辑是根据数据库检查提交的输入(使用HTTPclient请求)。 还使用debouncetime运算符,以尝试最大程度地减少服务器获得的请求量。

问题是,REST服务器根本没有收到任何获取请求。

TS代码如下:

import { Component, OnInit} from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import {matchOtherValidator} from '../match-other-validator';
import { HttpClient } from '@angular/common/http';
import { of } from 'rxjs';
import {map,debounceTime} from 'rxjs/operators';

const tzAsyncValidator = (http: HttpClient) => (c: FormControl)=>{
  console.log(c.value);
  if (!c|| String (c.value).length ===0){
    return of(null);
  }
  return http.get('http://localhost:4000/userIds/'+ String (c.value))
  .pipe(
    debounceTime(500),
    map((ids:any[])=>{
      console.log(ids);
      return ids.length ===1
      ? true : {exists:null};
    }),
  );
}

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

export class RegisterComponent implements OnInit { 
  public newUser;
  public verification;
  constructor(private http:HttpClient) { }



  ngOnInit() {
    this.newUser = new FormGroup({
      Tz: new FormControl ('',[Validators.required,Validators.minLength(4),Validators.maxLength(9),tzAsyncValidator(this.http)]),
      Email: new FormControl ('',[Validators.required,Validators.email]),
      PW: new FormControl ('', [Validators.required,Validators.pattern('^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$')]),
      PWVerification: new FormControl ('', [Validators.required,Validators.pattern('^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$'),matchOtherValidator('PW')])
    })

  }
  onSubmit() {

  }
}

任何输入将不胜感激,谢谢

1 个答案:

答案 0 :(得分:2)

异步验证器应该放在FormControl构造函数的第三个参数中。见下文。

ngOnInit() {
    this.newUser = new FormGroup({
        Tz: new FormControl('', // value or state
            [Validators.required, Validators.minLength(4),
                Validators.maxLength(9)],  // sync validators 2nd parameter
            [tzAsyncValidator(this.http)]), // async validators 3rd parameter
        ...
  })
}

有关更多信息,请参见this