Angular 6反应形式验证不起作用

时间:2018-08-19 21:32:07

标签: angular forms validation angular6 angular-reactive-forms

我通过尝试结合这两个教程来编写简单的登录表单:

但是我被困住了。验证无法按预期进行。我通过从组件到模板发送“消息”(即当我检查loginForm.value时的值)来解决该问题,但这不是它应该工作的方式。我在哪里出错了?

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


login.component.html

var hello = require('./hello.js');

login.component.ts

<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>

这是临时解决方法:

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";
      }
    }
  }

}

1 个答案:

答案 0 :(得分:2)

在您的html中,您使用的是* ngIf =“ submitted && ....但我看不到在onSubmit()上设置了提交

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

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

此外,一旦字段被触摸并变脏,您就可以检查验证

*ngIf="(f.dirty || f.touched) && f.errors"