Skip to content

Instantly share code, notes, and snippets.

@nicobytes
Last active March 12, 2023 21:34
Show Gist options
  • Save nicobytes/b37d79a9eb60fd931e59d1f9529052cf to your computer and use it in GitHub Desktop.
Save nicobytes/b37d79a9eb60fd931e59d1f9529052cf to your computer and use it in GitHub Desktop.

service

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor(
    private http: HttpClient
  ) { }

  checkEmail(email: string) {
    // simulate http.get()
    return of({ isEmailAvailable: email !== 'nicolas@gmail.com'})
      .pipe(delay(500));
  }
}

validations

static validateEmail(userService: UserService) {
    return (control: AbstractControl) => {
      const value = control.value;
      return userService.checkEmail(value)
      .pipe(
        map(response => {
          const isEmailAvailable = response.isEmailAvailable;
          return isEmailAvailable ? null : {notAvailable: true};
        })
      );
    };
  }
validateEmail(control: AbstractControl)  {
    const value = control.value;
    return this.userService.checkEmail(value)
    .pipe(
      map(response => {
        const isEmailAvailable = response.isEmailAvailable;
        return isEmailAvailable ? null : {notAvailable: true};
      })
    );
  }

html

<p class="help is-danger" *ngIf="emailField.hasError('notAvailable')">
  Es correo esta ocupado
</p>
@0x14Rp
Copy link

0x14Rp commented Apr 29, 2020

Good job bro 👌 Do you have any idea for dynamic validations that depend on other inputs?

@isaac-cobos
Copy link

Excelente Nico! Me vi tu video y esta espectacular tu explicacion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment