I am trying to create a custom form validator, but I keep getting this error Cannot read property 'value' of null. I have been really struggling with is issue for days now and here is my FormGroup:
this.step1Form = this.fb.group({
username: new FormControl('', {
validators: [Validators.required,
Validators.minLength(4),
this.checkUsername.bind(this)],
}),
email: new FormControl('', {
validators: [Validators.required,
Validators.pattern("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")],
}),
password: new FormControl('', {
validators: [Validators.required,
Validators.minLength(8)],
}),
repeat: new FormControl('', {
validators: [Validators.required,
Validators.minLength(8)],
}),
});
Here is my checkUsername method
checkUsername(g: FormGroup) {
return this.dataService.checkUsername(g.get('username').value).pipe(map(data => {
return typeof data["error"] != 'undefined' ? null : {'taken': true};
}));
}
and here is the checkUsername method in this.dataService
checkUsername(username):Observable<any> {
return this.http.get(globals.baseUrl+'/user/' + username, {headers:this.utilService.getHeadersJson()}).map(this.utilService.map);
}
And I get the error:
Cannot read property 'value' of null
on this line
return this.dataService.checkUsername(g.get('username').value).pipe(map(data => {
What am I doing wrong? I have tried without the pipe like so
checkUsername(g: FormGroup) {
return this.dataService.checkUsername(g.get('username').value).subscribe(data => {
return typeof data["error"] != 'undefined' ? null : {'taken': true};
});
}
but that didnt work, I have also tried my validator in different positions like so:
this.step1Form = this.fb.group({
username: new FormControl('', {
validators: [Validators.required,
Validators.minLength(4)],
}),
email: new FormControl('', {
validators: [Validators.required,
Validators.pattern("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")],
}),
password: new FormControl('', {
validators: [Validators.required,
Validators.minLength(8)],
}),
repeat: new FormControl('', {
validators: [Validators.required,
Validators.minLength(8)],
}),
}, { validator: this.checkUsername.bind(this)});
Also didnt work.
PLEASE HELP!
I have also tried this:
username: new FormControl('', {
validators: [Validators.required,
Validators.minLength(4)],
asyncValidator: [this.checkUsername.bind(this)],
}),
got this error:
Argument of type '{ validators: ValidatorFn[]; asyncValidator: any[]; }' is not assignable to parameter of type 'ValidatorFn | AbstractControlOptions | ValidatorFn[]'. Object literal may only specify known properties, and 'asyncValidator' does not exist in type 'ValidatorFn | AbstractControlOptions | ValidatorFn[]'.