Angular表单校验

执行ng generate component /form-check命令,生成相关表单测试用的组件
在这里插入图片描述
在·app.module.ts中引入相应的模块和组件
在这里插入图片描述

1. 编写form-check.component.html文件

<form [formGroup]="formGroup">
  <label>姓名<span class="star-span">*</span></label>
  <input type="text" formControlName="name" placeholder="姓名">
  <div *ngIf="name.invalid && (name.dirty || name.touched)" class="check-info">
      <div *ngIf="name.errors.required">
        必填项
      </div>
  </div>

<br/>
  <label>序号<span class="star-span">*</span></label>
  <input type="number" formControlName="serialNum" placeholder="不小于1的整数">
  <div *ngIf="serialNum.invalid && (serialNum.dirty || serialNum.touched)" class="check-info">
      <div *ngIf="serialNum.errors.required">
        必填项
      </div>
      <div *ngIf="serialNum.errors.pattern">
        不小于1的整数
      </div>
  </div>

<br/>
  <label>IP号<span class="star-span">*</span></label>
  <input type="text" formControlName="ip" placeholder="IP地址">
  <div *ngIf="ip.invalid && (ip.dirty || ip.touched)" class="check-info">
      <div *ngIf="ip.errors.required">
        必填项
      </div>
      <div *ngIf="ip.errors.pattern">
        IP格式不正确
      </div>
  </div>

<br/>
  <label>单选<span class="star-span">*</span></label>
  &nbsp;<span>A</span>&nbsp;&nbsp;<input type="radio" formControlName="radio" name="radio" value="A">
  &nbsp;<span>B</span>&nbsp;&nbsp;<input type="radio" formControlName="radio" name="radio" value="B">
  &nbsp;<span>C</span>&nbsp;&nbsp;<input type="radio" formControlName="radio" name="radio" value="C">
  <div *ngIf="radio.invalid && (radio.dirty || radio.touched)" class="check-info">
      <div *ngIf="radio.errors.required">
        必填项
      </div>
  </div>

<br/>
  <label>产品A<span class="star-span">*</span></label>
  <input type="text" formControlName="productA" placeholder="产品A名称" (blur)="checkA()" (keyup)="checkA()">
  <div *ngIf="infoA === 'notNull' || infoA === 'notEqual'" class="check-info">
    <div *ngIf="infoA === 'notEqual'">
          产品A不能与B同名
    </div> 
    <div *ngIf="infoA === 'notNull'">
          当单选为A或C不允许为空
    </div>
  </div>
<br/>
<label>产品B<span class="star-span">*</span></label>
  <input type="text" formControlName="productB" placeholder="产品B名称" (blur)="checkB()" (keyup) = "checkB()">
  <div *ngIf="infoB === 'notNull' || infoB === 'notEqual'" class="check-info">
    <div *ngIf="infoB === 'notEqual'">
          产品B不能与A同名
    </div> 
    <div *ngIf="infoB === 'notNull'">
          当单选为A或B不允许为空
    </div>
  </div>
<br/>
  <button (click)="checkAll()">提交</button>
</form>

2. 编写form-check.component.css文件

.star-span {
  color: red;

}

.check-info {
  color: red;
  height: 14px;
  font-size: 10px;
  display: block;
}

3. 编写form-check.component.ts文件

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

@Component({
  selector: 'app-form-check',
  templateUrl: './form-check.component.html',
  styleUrls: ['./form-check.component.css']
})
export class FormCheckComponent implements OnInit {
   minInt1Reg = '^[0-9]*[1-9][0-9]*$';
   minInt0Reg = '^\\d+$';
   ipReg = '^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$';
  formGroup = new FormGroup({
    'name': new FormControl('', 
    [Validators.required]),
    'serialNum': new FormControl('', 
    [Validators.required, Validators.pattern(this.minInt1Reg)]),
    'ip': new FormControl('',
    [Validators.required, Validators.pattern(this.ipReg)]),
    'radio': new FormControl('',  [Validators.required]),
    'productA': new FormControl(''),
    'productB': new FormControl('')
  });
  get name() { return this.formGroup.get('name'); }
  get serialNum() { return this.formGroup.get('serialNum'); }
  get ip() { return this.formGroup.get('ip'); }
  get radio() { return this.formGroup.get('radio'); }
  get productA() {return this.formGroup.get('productA'); }
  get productB() {return this.formGroup.get('productB'); }
  infoA = '';
  infoB = '';

  constructor() { }

  ngOnInit() {
  }

  checkA(){
    this.infoA = '';
    const radioVal = this.formGroup.get('radio').value;
    const productA = this.formGroup.get('productA').value;
    const productB = this.formGroup.get('productB').value;
    if(productA === productB) {
      this.infoA = 'notEqual';
      return false;
    }
    if((radioVal === 'A' || radioVal === 'C') && productA.length === 0){
      this.infoA = 'notNull';
      return false;
    }
    return true;
  }

  checkB() {
    this.infoB = '';
    const radioVal = this.formGroup.get('radio').value;
    const productA = this.formGroup.get('productA').value;
    const productB = this.formGroup.get('productB').value;
    if(productB === productA) {
      this.infoB = 'notEqual';
      return false;
    }
    if((radioVal === 'A' || radioVal === 'B') && productB.length === 0){
      this.infoB = 'notNull';
      return false;
    }
    return true;
  }

  checkAll(){
    Object.values(this.formGroup.controls).forEach(i=>{
      i.markAsDirty();
    })
    this.formGroup.patchValue(this.formGroup.getRawValue())
    const isA = this.checkA();
    const isB = this.checkB();
    if(this.formGroup.valid && isA && isB){
      console.log('校验通过');
      // 提交数据
      const isSubmit = window.confirm('确认提交么?');
      if(isSubmit){
        this.submit();
      }else{
        console.log('取消提交...');
      }
      return false;
    }else{
      console.log('校验不通过');
      return true;
    }
  }

  submit() {
    console.log('已提交...');
  }
}

效果图

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值