代码之家  ›  专栏  ›  技术社区  ›  Nenad Bulatović

角6反作用形式验证不起作用

  •  1
  • Nenad Bulatović  · 技术社区  · 6 年前

    我正在编写一个简单的登录表单,尝试结合以下两个教程:

    但我被卡住了。验证无法按预期工作。我通过将“消息”(即,当我检查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;
        }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Obed Amoasi    6 年前

    在html中,您使用的是*ngIf=“submitted&。。。。但是我没有看到submit()设置submit()

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

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

    而且,一旦字段被触碰并弄脏,就可以检查验证

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