Form validation with api call?


#1

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
HTML:

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

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

TS:

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

AUTH:

  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) => {
          resolve(res);
        }, (err) => {
          reject(err);
        });
    });
  }

checkEmail looks same just with different api address.


#2

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 = formBuilder.group({
  userName: ['', [Validators.pattern('[a-zA-Z]+'), checkUserName]
}); 

#3

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


#4

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