angular验证器Validators及自定义验证器方法

angular验证器Validators及自定义验证器方法

Laughing
2021-09-06 / 0 评论 / 1,695 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2024年03月16日,已超过307天没有更新,若内容或图片失效,请留言反馈。

angular预置验证器

angular在Validators类中预置了部分验证器。
可以通过如下代码导入

import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';

比如,我们使用一下必填验证required
首先看下ts代码,在ts文件中,我们通过注入FormBuilder,创建一个FormGroup,在FormGroup中添加一个名称为skuFormControl,然后我们校验sku,要求用户必须输入。

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-demo-form-sku-form-builder',
  templateUrl: './demo-form-sku-form-builder.component.html',
  styleUrls: ['./demo-form-sku-form-builder.component.css']
})
export class DemoFormSkuFormBuilderComponent implements OnInit {

  myForm: FormGroup

  constructor(formBuilder: FormBuilder) {

    this.myForm = formBuilder.group({})
    let formControl: FormControl = new FormControl("", Validators.required)
    this.myForm.addControl("sku", formControl)
  }

  ngOnInit(): void {
  }

  onSubmit(form: any): void {
    console.log(form)
  }

}

html代码如下

<nz-card style="width:300px;">
    <form [formGroup]="myForm" nz-form (ngSubmit)="onSubmit(myForm.value)">
        <nz-form-item>
            <nz-form-label [nzSpan]="6" nzFor="sku">sku</nz-form-label>
            <nz-form-control [nzSpan]="14">
                <input nz-input name="sku" type="text" id="sku" [formControl]="myForm.controls['sku']">
                <nz-tag *ngIf="!myForm.controls['sku'].valid && myForm.controls['sku'].touched" [nzColor]="'magenta'">请输入SKU</nz-tag>
            </nz-form-control>
        </nz-form-item>
        <nz-form-item>
            <button type="submit" nz-button class="primary">Submit</button>
        </nz-form-item>
    </form>
</nz-card>

myForm.controls['sku'].valid用于校验用户是否输出,myForm.controls['sku'].touched判断用户是否点击了控件。如果用户点击控件后,没有输入内容。

自定义验证器

自定义验证器其实就是一个方法,这个方法有如下特点:

  1. 接收一个FormControl作为参数
  2. 验证失败时,返回一个StringMap<string,boolean>对象,键是错误代码、值是true
    ts文件如下

    import { Component, OnInit } from '@angular/core';
    import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
    
    @Component({
      selector: 'app-demo-form-sku-form-builder',
      templateUrl: './demo-form-sku-form-builder.component.html',
      styleUrls: ['./demo-form-sku-form-builder.component.css']
    })
    export class DemoFormSkuFormBuilderComponent implements OnInit {
    
      myForm: FormGroup
    
      constructor(formBuilder: FormBuilder) {
    
     this.myForm = formBuilder.group({})
     let formControl: FormControl = new FormControl("", Validators.compose(
       [Validators.required, this.skuValidator]
     ))
     this.myForm.addControl("sku", formControl)
      }
    
      ngOnInit(): void {
      }
    
      onSubmit(form: any): void {
     console.log(form)
      }
    
      skuValidator(formControl: FormControl): { [s: string]: boolean } {
     if (!formControl.value.match(/^123/)) {
       return { invalidSku: true }
     }
     return { invalidSku: false }
      }
    
    }

    html代码如下

    <nz-card style="width:300px;">
     <form [formGroup]="myForm" nz-form (ngSubmit)="onSubmit(myForm.value)">
         <nz-form-item>
             <nz-form-label [nzSpan]="6" nzFor="sku">sku</nz-form-label>
             <nz-form-control [nzSpan]="14">
                 <input nz-input name="sku" type="text" id="sku" [formControl]="myForm.controls['sku']">
                 <nz-tag *ngIf="myForm.controls['sku'].hasError('required') && myForm.controls['sku'].touched" [nzColor]="'magenta'">请输入SKU</nz-tag>
                 <nz-tag nzColor="error" *ngIf="myForm.controls['sku'].hasError('invalidSku')">
                     <i nz-icon nzType="close-circle"></i>
                     <span>error</span>
                   </nz-tag>
             </nz-form-control>
         </nz-form-item>
         <nz-form-item>
             <button type="submit" nz-button class="primary">Submit</button>
         </nz-form-item>
     </form>
    </nz-card>

    如果我们输入的sku不是123开头,可以看到以下页面

1

评论 (0)

取消