简体   繁体   English

自定义验证器Angular 2

[英]Custom Validator Angular 2

I've written a web api function that takes a username from the textfield and checks if the username is already taken. 我编写了一个web api函数,它从文本字段中获取用户名并检查用户名是否已被占用。 To know if the username is available or not, my server returns Y if it is available and N if its not. 要知道用户名是否可用,我的服务器返回Y如果可用)和N如果不可用)。

To validate the username, I'm using a ValidatorFn in Angular2 so validate the input. 要验证用户名,我在Angular2中使用ValidatorFn,以验证输入。 However, my validator function is not working. 但是,我的验证器功能不起作用。

Here is the validator function: 这是验证器功能:

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

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

Here is the isAvailable function: 这是isAvailable函数:

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
}

Form Builder: 表单生成器:

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) is failing and I'm getting this error: 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),

But that is factory function call and not a validator function call. 但那是工厂函数调用而不是验证器函数调用。 During initialization they return ValidatorFn : 在初始化期间,它们返回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 . 在官方文档中查看更多内容。

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 . 而且我认为你不需要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]]
})

Regarding the error: 关于错误:

Type '{ valid: boolean; 输入'{valid:boolean; }' is not assignable to type ValidatorFn . }'不能赋值为ValidatorFn

You need to use the correct return type ValidationErrors instead of ValidatorFn : 您需要使用正确的返回类型ValidationErrors而不是ValidatorFn

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM