Witam mam problem z stworzeniem walidatora, który sprawdzałby czy po wpisaniu w polu formularza podany "username" istnieje już w bazie.
W tym celu stworzyłem w web api metodę która sprawdza, czy użytkownik istnieje w bazie w zależności od wartości podanej zwróci true lub false.
[HttpGet]
[AllowAnonymous]
[Route("api/CheckIfExist/{username}")]
public async Task <HttpResponseMessage> CheckIfExist(string username)
{
var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext());
var manager = new UserManager<ApplicationUser>(userStore);
var result = await userStore.FindByNameAsync(username);
if (result == null)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, false.ToString());
}
else
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, true.ToString());
}
}
Następnie stworzyłem w angularze serwis który przechwytuje dane pochodzące z web api:
readonly rootUrl = 'http://localhost:61923';
constructor(private http: HttpClient) { }
registerUser(user: User) {
const body: User = {
UserName: user.UserName,
Password: user.Password,
Email: user.Email,
FirstName: user.FirstName,
LastName: user.LastName
};
const reqHeader = new HttpHeaders({'No-auth': 'True'});
return this.http.post(this.rootUrl + '/api/User/Register', body, {headers: reqHeader});
}
CheckUsernameIfExist(user: User) {
return this.http.post(this.rootUrl + '/api/CheckIfExist/', JSON.stringify({ username: user.UserName}))
.map((res: Response) => {
return res.json().status; }
);
}
I na końcu komponent rejestracji. Wykorzystałem ReactiveForms do zbudowania formularza i przekazania walidatorów:
ngOnInit() {
this.formInitBuilder();
}
formInitBuilder() {
this.form = this.formBuilder.group ({
UserName: new FormControl('', [Validators.required], this.validateUserNameTaken.bind(this)),
Password: new FormControl('', [ Validators.required, Validators.minLength(3)]),
Email: new FormControl('', [Validators.required, Validators.email]),
FirstName: new FormControl(),
LastName: new FormControl()
});
}
// Walidator
validateUserNameTaken(control: AbstractControl) {
return this.userService.CheckUsernameIfExist(control.value).map(res => {
return res ? null : { userName: true };
});
}
html:
<form class="main-form needs-validation" [formGroup]="form" >
<div class="row">
<div class="col">
<div class="form-group">
<input type="text" class="form-control" name="UserName" formControlName="UserName" required>
<div *ngIf="form.get('UserName').errors && form.get('UserName').errors.userName">
Podany nick jest już zajęty
</div>
</div>
</div>
W html wyrzuca mi błąd:
Identifier 'userName' is not defined. '__type' does not contain such a member
przy linijce form.get('UserName').errors.userName
.
A w konsoli w Chrome: POST http://localhost:61923/api/CheckIfExist/ 404 (Not Found)
Walidator zrobiłem na podstawie tego artykułu: https://alligator.io/angular/async-validators/
W bazie danych są wartości a requesty zrobione w postmanie wykonują się poprawnie.