自定义验证器角度2 [英] Custom Validator Angular 2

查看:89
本文介绍了自定义验证器角度2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个Web api函数,该函数从文本字段中获取用户名,并检查该用户名是否已被使用.要知道用户名是否可用,我的服务器将返回Y(如果可用),并返回N(如果没有).

I've written a web api function that takes a username from the textfield and checks if the username is already taken. To know if the username is available or not, my server returns Y if it is available and N if its not.

要验证用户名,我在Angular2中使用ValidatorFn,因此请验证输入.但是,我的验证器功能不起作用.

To validate the username, I'm using a ValidatorFn in Angular2 so validate the input. However, my validator function is not working.

这是验证器功能:

interface Validator<T extends FormControl> {
  (c: T): { [error: string]: any };
}

function validateUsername(c: string) : ValidatorFn {
  return (this.isAvailable(c)=='Y') ? null : {
    validateUsername: {
      valid: false
    }
  };
}

这是isAvailable函数:

Here is the isAvailable function:

private isAvailable(username: string) {
  let usernameAvailable;
  let url = 'URL/api/auth/checkuser/' + username;
  let headers = new Headers();
  headers.append('User', sessionStorage.getItem('username'));
  headers.append('Token', sessionStorage.getItem('token'));
  headers.append('AccessTime', sessionStorage.getItem('AccessTime'));

  let options = new RequestOptions({ headers: headers });

  this.http.get(url, options)
    .subscribe((res: Response) => usernameAvailable);
  return usernameAvailable; //returns Y or N
}

表单生成器:

complexForm: FormGroup;
constructor(private http: Http, fb: FormBuilder) {

  this.complexForm = fb.group({
    'username': [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(10), validateUsername(this.complexForm.controls['username'].value)])],
  })
}

validateUsername(this.complexForm.controls['username'].value)失败,出现此错误:

[ts] Type '{ validateUsername: { valid: boolean; }; }' is not assignable to type 'ValidatorFn'.   Object literal may only specify known properties, and 'validateUsername' does not exist in type 'ValidatorFn'. (property) validateUsername: {
    valid: boolean;
}

推荐答案

您没有正确添加验证器函数.注册时无需调用函数:

You not adding your validator function correctly. You don't need to call your function when you register it:

this.complexForm = fb.group({
  'username': [null, Validators.compose(
    [
      Validators.required,
      Validators.minLength(5),
      Validators.maxLength(10),
      validateUsername    <----- don't call it here
    ]
  )],
})

您会看到一些函数被称为:

You can see that some functions are called:

Validators.minLength(5),

但这是工厂函数调用,而不是验证程序函数调用.在初始化期间,它们返回ValidatorFn:

But that is factory function call and not a validator function call. During initialization they return ValidatorFn:

  /**
   * Validator that requires controls to have a value of a minimum length.
   */
  static minLength(minLength: number): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
       ...
  }

在官方文档中查看更多 .

See more in the official docs.

此外,看来您的验证器是异步的,因此您必须在异步数组中传递它.而且我认为您不需要Validators.compose.因此,正确的配置应如下所示:

Also, it seems that your validator is async, so you have to pass it in the async array. And I don't think you need Validators.compose. The correct configuration should therefore be like this:

this.complexForm = fb.group({
  'username': [null, [
    Validators.required,
    Validators.minLength(5),
    Validators.maxLength(10),
  ], [validateUsername]]
})

关于错误:

类型'{有效:布尔值; }'不能分配给ValidatorFn类型.

您需要使用正确的返回类型ValidationErrors而不是ValidatorFn:

You need to use the correct return type ValidationErrors instead of ValidatorFn:

function validateUsername(c: string) : ValidationErrors {
  return (this.isAvailable(c)=='Y') ? null : {
    validateUsername: {
      valid: false
    }
  };
}

这篇关于自定义验证器角度2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆