1

Am new to angular2 and i would like to validate an email address from the server but it fails

This is my form

this.userform = this._formbuilder.group({
  email: ['', [Validators.required], [this._validationService.emailExistsValidator.bind(this)]],
});

Then the _ValidationService i have The validation service is a service with @Injector

  @Injectable()
   export class ValidationService{

  constructor(
private _authService:AuthService
  ){}

 emailExistsValidator(control) {
   if (control.value != undefined) {
    return this._authService.checkExists("email")
      .map(response => {
       if (!response) {
          return {'emailNotExists': true};
        }
      });
     }
  }
}

And in the authservice i have (which is another service performing the http requests)

@Injectable()
 export class AuthService {

checkExists(value):Observable<any>{
return this._http.get(this.authurl+value)
  .map(response => {
   return response  //this is either true or false
  });
 }

}

I have followed This link in setting up my form but it fails

The error returned is

Cannot read property 'checkExists' of undefined
at UsersComponent.webpackJsonp.187.
 ValidationService.emailExistsValidator

What could be wrong

2
  • You need to provide more context for your code. Where is the emailExistsValidator() method located? How is this._authService instantiated? Commented Jan 29, 2017 at 14:29
  • Sorry ive updated the question all these are different services, this._authservice is instantiated in the constructor Commented Jan 29, 2017 at 14:42

1 Answer 1

1

If this should point to the ValidationService, bind() needs to be

this.userform = this._formbuilder.group({
  email: ['', [Validators.required], [this._validationService.emailExistsValidator.bind(this._validationService)]],
});
Sign up to request clarification or add additional context in comments.

2 Comments

The other issue now comes in i would like to validate only after the user has completed entering the email, currently works on every key pressed, How do i do that
Just hide the validation error while you don't want the user to see it. Like showEmailValidation:boolean = false; <input (blur)="showEmailValidation = true" ...>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.