【问题标题】:Trying to validate that no field is empty in angular 6试图验证角度 6 中没有字段为空
【发布时间】:2019-08-31 13:32:59
【问题描述】:

我正在尝试用 angular 创建一个简单的用户注册项目。我正在尝试验证表单中没有任何字段为空。但是我无法这样做。

这是我的 ts 代码:

export class AdduserComponent implements OnInit {


  constructor(private formBuilder:FormBuilder,private userService:UsersService,private router:Router) { }
  addForm: FormGroup;
  selected = 'option2';

  ngOnInit() {

    this.addForm = this.formBuilder.group({
      id: [],
      userName: ['', Validators.required],
      password: ['', Validators.required],
      userRole:['',Validators.required],
    });
  }
  onSubmit() {
    this.userService.createUser(this.addForm.value)
      .subscribe( data => {
        this.router.navigate(['adduser']);
      });
    console.log(this.addForm.value);
  }
  changeClient(value) {
    console.log(value);
}
}

这是我的模板:

<form [formGroup]="addForm" class="login-form" (ngSubmit)="onSubmit()">
    <div class="form-group">
        <mat-form-field class="example-full-width">

      <input matInput type="text" formControlName="userName" placeholder="userName" name="userName" class="form-control" id="userName">
        </mat-form-field>
    </div>

    <div class="form-group">
        <mat-form-field class="example-full-width">

      <input matInput type="password" formControlName="password" placeholder="Password" name="password" class="form-control" id="password">
    </mat-form-field>
    </div>

    <mat-form-field>
        <mat-select panelClass="example-panel-blue.mat-select-panel" placeholder="Roles" formControlName="userRole" id="userRole" (selectionChange)="changeClient($event.value)" [(value)]="selected">
          <mat-option value="Admin">Admin</mat-option>


        </mat-select>
      </mat-form-field>
      <div class="container" style="margin: 12px" fxLayout="row" fxLayoutAlign="center center">


    <button mat-raised-button color="primary">Create</button>
      </div>
  </form>

我已经添加了验证器,但我仍然可以使用空值创建用户。请帮助。提前致谢

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    只要表单中的任何值发生变化,您就可以验证您的数据,无需等待提交。

    这是一个验证非空格字符串的示例,您可以根据需要进行更改。

    game-start.component.ts

    import { Component, OnInit } from '@angular/core';
    import { FormGroup, FormControl, Validators } from '@angular/forms';
    
    @Component({
      selector: 'app-game-start',
      templateUrl: './game-start.component.html',
      styleUrls: ['./game-start.component.css']
    })
      
    export class GameStartComponent implements OnInit {
      playerInfo = new FormGroup({
        playerOneName: new FormControl('', [Validators.required, this.WhitespacesInvalid]),
        playerTwoName: new FormControl('', [Validators.required, this.WhitespacesInvalid]),
      });
    
      constructor() {  }
    
      public WhitespacesInvalid(control: FormControl) {
        const isWhitespace = (control.value || '').trim().length === 0;
        const isValid = !isWhitespace;
        return isValid ? null : { 'whitespaceInvalid': true };
      }
    
      ngOnInit(): void {
      }
    
      onSubmit() {
        // TODO: Use EventEmitter with form value
        console.warn(this.playerInfo.value);
        console.warn(this.playerInfo);
      }
    }
    

    在构造函数中创建FormControls时声明并使用了WhitespacesInvalid自定义验证器

    在 HTML 中,hasError 函数用于在表单中的值发生更改时检查'whitespaceInvalid',无需等待提交发生,并且提交按钮仅在所有验证器都启用时才启用没问题。

    game-start.component.html

    <h2>Welcome to Game of Drones</h2>
    <h2>Enter Player's Names</h2>
    
    <form [formGroup]="playerInfo" (ngSubmit)="onSubmit()">
      <label>
        Player 1:
        <input type="text" formControlName="playerOneName">
      </label>
    
      <label>
        Player 2:
        <input type="text" formControlName="playerTwoName">
      </label>
    
      <button type="submit" [disabled]="!playerInfo.valid">START</button>
    
      <div *ngIf="playerInfo.controls['playerOneName'].hasError('whitespaceInvalid')" class="alert alert-danger">
        Player 1 name can not be empty.
      </div>
    
      <div *ngIf="playerInfo.controls['playerTwoName'].hasError('whitespaceInvalid')" class="alert alert-danger">
        Player 2 name can not be empty.
      </div>
    
    </form>
    

    自定义验证器取自这个问题。

    How to validate white spaces/empty spaces? [Angular 2]

    【讨论】:

      【解决方案2】:

      您必须自己检查表单是否有效,它不会阻止您提交 - https://angular.io/api/forms/NgForm:

        onSubmit() {
          if(this.addForm.valid) {
            this.userService.createUser(this.addForm.value)
              .subscribe( data => {
                this.router.navigate(['adduser']);
              });
            console.log(this.addForm.value);  
           }
        }
      

      【讨论】:

        【解决方案3】:

        无效的表单不会阻止您触发(ngSubmit)

        onSubmit() 中进行表单有效性检查,然后创建用户。

        onSubmit() {
            if (this.addForm.valid) {
                  this.userService.createUser(this.addForm.value)
                  .subscribe( data => {
                           this.router.navigate(['adduser']);
                  });
            }
        }
        

        【讨论】:

        • 如果你想立即得到错误意味着不等待提交或者说点击提交你可以这样做:stackblitz.com/angular/…
        • @NirajOza 是的,还没有处理材料,但是这个ErrorStateMatcher 很好。我通过检查表单的touched 属性的值和控件的错误以及其他一些标志来显示错误消息可能是。谢谢!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-16
        • 2016-01-14
        • 2018-08-18
        • 1970-01-01
        • 1970-01-01
        • 2020-01-29
        相关资源
        最近更新 更多