Skip to content

Instantly share code, notes, and snippets.

@mike1477
Last active March 23, 2020 12:56
Show Gist options
  • Save mike1477/4bea1933d29cd8c6483c9d0aacec7c42 to your computer and use it in GitHub Desktop.
Save mike1477/4bea1933d29cd8c6483c9d0aacec7c42 to your computer and use it in GitHub Desktop.
Reactive Angular Unique Username Validator
//Import
import { HttpClientModule } from "@angular/common/http";
imports: [
...,
...,
...,
HttpClientModule
],
//Imports
import { HttpClient } from "@angular/common/http";
import { map} from "rxjs/operators";
//This goes into service
validateUsernameNotTaken(control: AbstractControl) {
return this.checkUsernameNotTaken(control.value).pipe(
map(res => {
return res ? null : { usernameTaken: true };
})
);
}
//Fake API call -- You can have this in another service
checkUsernameNotTaken(username: string) {
return this.http.get("assets/fakedb.json").pipe(
map((usernameList: Array<any>) =>
usernameList.filter(user => user.username === username)
),
map(users => !users.length)
);
}
[
{
"username": "admin"
},
{
"username": "superuser"
},
{
"username": "user"
},
{
"username": "user123"
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment