forms - Custom Validator Angular 2 -
i've written web api function takes username textfield , checks if username taken. know if username available or not, server returns y
if available , n
if not.
to validate username, i'm using validatorfn in angular2 validate input. however, validator function not working.
here validator function:
interface validator<t extends formcontrol> { (c: t): { [error: string]: }; } function validateusername(c: string) : validatorfn { return (this.isavailable(c)=='y') ? null : { validateusername: { valid: false } }; }
here 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 }
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)
failing , i'm getting error:
[ts] type '{ validateusername: { valid: boolean; }; }' not assignable type 'validatorfn'. object literal may specify known properties, , 'validateusername' not exist in type 'validatorfn'. (property) validateusername: { valid: boolean; }
you not adding validator function correctly. don't need call function when register it:
this.complexform = fb.group({ 'username': [null, validators.compose( [ validators.required, validators.minlength(5), validators.maxlength(10), validateusername <----- don't call here ] )], })
you can see functions called:
validators.minlength(5),
but factory function call , not validator function call. during initialization return validatorfn
:
/** * validator requires controls have value of minimum length. */ static minlength(minlength: number): validatorfn { return (control: abstractcontrol): validationerrors | null => { ... }
see more in official docs.
also, seems validator async, have pass in async array. , don't think need validators.compose
. correct configuration should therefore this:
this.complexform = fb.group({ 'username': [null, [ validators.required, validators.minlength(5), validators.maxlength(10), ], [validateusername]] })
regarding error:
type '{ valid: boolean; }' not assignable type
validatorfn
.
you need use correct return type validationerrors
instead of validatorfn
:
function validateusername(c: string) : validationerrors { return (this.isavailable(c)=='y') ? null : { validateusername: { valid: false } }; }
Comments
Post a Comment