Angular 6 Reactive Form Validation不起作用

问题描述 投票:1回答:1

我正在编写简单的登录表单,尝试将这两个教程组合在一起:

但我被卡住了。验证无法按预期工作。我通过从组件到模板发送“message”(即,当我检查loginForm.value的值时)发出了一种解决方法,但这不是它应该如何工作的。我哪里出错了?

这是我无法工作的代码的一部分:


login.component.html

<div class="container">
  <div class="col-md-6">
    <h2>Log In</h2>
    <hr>
    <p *ngIf="message" class="text-center error">{{message}}</p>
    <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">

      <div class="form-group clearfix" [ngClass]="{ 'has-error': submitted && f.userid.errors }">
        <label for="userid" class="col-md-3 col-sm-5 col-xs-12">Userid</label>

        <div class="col-md-9 col-sm-7 col-xs-12">
          <input type="text" class="form-control" formControlName="userid" />
          <div *ngIf="submitted && f.userid.errors" class="help-block">
            <div *ngIf="f.userid.errors.required">Userid is required</div>
          </div>
        </div>
      </div>

      <div class="form-group clearfix" [ngClass]="{ 'has-error': submitted && f.password.errors }">
        <label for="password" class="col-md-3 col-sm-5 col-xs-12">Password</label>

        <div class="col-md-9 col-sm-7 col-xs-12">
          <input type="password" class="form-control" formControlName="password" />
          <div *ngIf="submitted && f.password.errors" class="help-block">
            <div *ngIf="f.password.errors.required">Password is required</div>
          </div>
        </div>
      </div>

      <div class="col-xs-12 form-group text-right">
        <button class="btn btn-success" type="submit">Login</button>
      </div>

    </form>
  </div>
</div>

login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { Login } from '../login';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  model: Login = { userid: "admin", password: "nenad123" };
  loginForm: FormGroup;
  message: string;
  returnUrl: string;

  constructor(private formBuilder: FormBuilder, private router: Router, public authService: AuthService) { }

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      userid: ['', Validators.required],
      password: ['', Validators.required]
    });

    this.returnUrl = '/home';
    this.authService.logout();
  }

  get f() { return this.loginForm.controls; }

  onSubmit() {

    if (this.loginForm.invalid) {
      let user = this.loginForm.value.userid;
      let pass = this.loginForm.value.password;
      if (user == "" && pass == "") { this.message = "UserId and Password cannot be empty"; }
      else if (user == "") { this.message = "UserId cannot be empty"; }
      else if (pass == "") { this.message = "Password cannot be empty"; }
      else { this.message = "Please check your userid and password"; }
      return;
    }
    else {
      if (this.f.userid.value == this.model.userid && this.f.password.value == this.model.password) {
        localStorage.setItem('isLoggedIn', "true");
        localStorage.setItem('token', this.f.userid.value);
        this.router.navigate([this.returnUrl]);
      }
      else {
        this.message = "Please check your userid and password";
      }
    }
  }

}

这部分是临时解决方法:

if (this.loginForm.invalid) {
      let user = this.loginForm.value.userid;
      let pass = this.loginForm.value.password;
      if (user == "" && pass == "") { this.message = "UserId and Password cannot be empty"; }
      else if (user == "") { this.message = "UserId cannot be empty"; }
      else if (pass == "") { this.message = "Password cannot be empty"; }
      else { this.message = "Please check your userid and password"; }
      return;
    }
angular forms validation angular6 angular-reactive-forms
1个回答
2
投票

在你的HTML中你使用* ngIf =“提交&& ....但我没有看到提交被设置onSubmit()

    onSubmit() {
        this.submitted = true;
        // rest of code goes here
    }

您可以考虑将此添加到onSubmit()方法

此外,您可以在触摸和弄脏字段后检查验证

*ngIf="(f.dirty || f.touched) && f.errors"
© www.soinside.com 2019 - 2024. All rights reserved.