Walidacja formularza – istnienie nazwy użytkownika w bazie danych

0

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.

0

Twój angularowy http client wysyła posta a ty masz w kontrolerze get. Może to z tym jest problem.
chyba coś takiego:

 return this.http.get(this.rootUrl + '/api/CheckIfExist/' + user.UserName)
0

Usunąłem InternalServerError z request w Web API ponieważ w konsoli wyrzucało błąd :

        [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( false.ToString());
            }
            else
            {
                return Request.CreateResponse(true.ToString());
            } 

Przerobiłem w serwisie zapytanie get:

 CheckUsernameIfExist(userName) {
   return this.http.get(this.rootUrl + '/api/CheckIfExist/' + userName);

I w formularzu html:

form.get('UserName').errors['userName'] 

Nie mam żadnych błędów w visual studio i konsoli Chrome ale walidator nie działa.
Sprawdziłem też w debugerze jakie dane otrzymuje walidator dla userName= abc dostaje true tak jak powinno być ponieważ ten nick jest już w bazie ale nie wyrzuca komunikatu "Podany nick jest już zajęty ".

1 użytkowników online, w tym zalogowanych: 0, gości: 1