Form validation with api call?


How to use form validation with api calls to check if data is correct? Whenever I enter this signup page I got errors like:
Cannot read property 'put' of undefined
Cannot read property 'http' of undefined

<ion-content padding>
  <p *ngIf="submitAttempt" style="color: #ea6153;">Please fill out all details accurately.</p>
  <ion-list inset>
    <form [formGroup]="signupForm">
        <ion-input formControlName="userName" [(ngModel)]="userName" placeholder="UserName" type="text"></ion-input>
        <ion-input formControlName="email" [(ngModel)]="email" placeholder="Email" type="email"></ion-input>

        <ion-input formControlName="password" [(ngModel)]="password" placeholder="Password" type="password"></ion-input>
    <button ion-button block (click)="register()">Register</button>


this.signupForm ={
      userName: ['', Validators.compose([Validators.required, Validators.pattern('[a-zA-Z]*')]), this.authService.checkUserName],
      email: ['', this.authService.checkEmail],
      password: ['']


  checkUserName(control: FormControl): any {
    return new Promise((resolve, reject) => {

      let headers = new Headers();
      headers.append('Content-Type', 'application/json');

      this.http.put('http://localhost:63203/api/Customers/CheckIfUserExist', JSON.stringify(control.value), { headers: headers })
        .subscribe((res) => {
        }, (err) => {

checkEmail looks same just with different api address.


Before we get to the question at hand, a couple of things:

  • since you’re using reactive forms, you are better off using formControlName instead of [(ngModel)} for binding
  • there is no need to instantiate a promise here, you can just return http.put() (or use the map operator to massage it into proper form)

Now, for the actual issue: all object-oriented stuff in JavaScript is really smoke and mirrors. There is no language support for any of it. As a result, inside methods, frequently this isn’t what you’re expecting it to be, and I suspect this is one of those situations.

Instead of passing functions, use lambdas:

let checkUserName = (ctrl) => this.authService.checkEmail(ctrl);
this.signupForm ={
  userName: ['', [Validators.pattern('[a-zA-Z]+'), checkUserName]


could you show me an example of correctly made checkUserName method? Because I still have some problems


I thought I already did. You don’t want to make it a method.