Username already exists, please check for available options during sign up

Anil picture Anil · Mar 26, 2018 · Viewed 12.5k times · Source

I am creating an angular app in which a user can register. But while registering I request him for some details like email, mobile number and all. Also, a username which he can choose. But here I want to do a check on the username as soon as he entered and display an error like," this username already exists in our database".

I have mysql database and front end with angular 4. I am new to this angular development, please help me how can i do this?

Here is a sample image for google sign up, enter image description here

Answer

xeofus picture xeofus · Mar 26, 2018

You can use AsyncValidator and asynchronous-validation-in-angulars

Or my implementation:

Form initialize:

this.form = this.formBuilder.group({
  username: [{value: null, disabled: false}, 
    [Validators.required, this.validateUsername()]]
})

Custom validator:

private validateUsername(): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} => {
      this.someServiceWorkingWithDatabase.checkUsername(control)
        .subscribe(
          ({data}) => {
            let res: string = data;
            if (res === control.value) {
              return {'alreadyExist': true};
            } else {
              return null
            }
          },
          (error) => {
            console.log(error);
          }
        )
    }
}

Template:

<div class="formError" *ngIf="this.form['controls']
  .username.hasError('alreadyExist')">
    *this username already exists in our database</div>