响应式表单验证

这篇博客详细介绍了如何在Angular应用中使用响应式表单进行用户输入验证,包括自定义同步和异步验证器的实现。通过示例代码展示了如何设置必填项、最小长度限制以及手机号码验证。同时,文章还涵盖了验证状态的显示和错误信息的处理,帮助开发者理解并掌握Angular表单验证机制。
摘要由CSDN通过智能技术生成

reactiveRegist.css

.ng-invalid {
  border: 1px solid red;
}
.hasErr {
  border: 1px solid red;
}

reactiveRegist HTML

<form [formGroup]="formModel" (submit)="onSubmit()">
  <div>用户名:<input [class.hasErr]="formModel.get('username').invalid && formModel.get('username').touched"
                  type="text" formControlName="username"></div>
    <div [hidden]="formModel.get('username').valid ||  formModel.get('username').untouched">
      <!--  required, minlengh 是关键字,不是名称‘ -->
      <div [hidden]="!formModel.hasError('required','username')">
        <p >用户名是必填项!</p>
      </div>

      <div [hidden]="!formModel.hasError('minlength','username')">
        <p >用户名最小长度是5!</p>
      </div>
    </div>
  <div>手机号码:<input type="number" formControlName="mobile"></div>
  <div  [hidden]="formModel.get('mobile').valid || formModel.get('mobile').pristine">
    <div [hidden]="!formModel.hasError('mobilenumber','mobile')">
      <p >请输入正确的手机号</p>
    </div>
  </div>
  <div [hidden]="!formModel.get('mobile').pending">
      正在验证手机的合法性。。。
  </div>
  <div formGroupName="passwordsGroup">
    <div>密码:<input type="password" formControlName="password"></div>
    <div [hidden]="!formModel.hasError('minlength',['passwordsGroup','password'])">
      <p >密码最小长度是5!</p>
    </div>
    <div>确认密码:<input type="password" formControlName="pconfirm"></div>
  </div>
  <div [hidden]="!formModel.hasError('equal','passwordsGroup')">
    <p >{{this.formModel.getError('equal','passwordsGroup')?.descxxx}}</p>
  </div>
  <button type="submit">注册</button>
</form>
<div>
  {{formModel.status}}
</div>

reactiveRegist.TS

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {mobileAsyncValidator, mobileValidator} from '../validator/validators';

@Component({
  selector: 'app-reactive-regist',
  templateUrl: './reactive-regist.component.html',
  styleUrls: ['./reactive-regist.component.css']
})
export class ReactiveRegistComponent implements OnInit {

  formModel: FormGroup;
  constructor(fb: FormBuilder) {
    this.formModel = fb.group({
      username: ['name', [Validators.required, Validators.minLength(5)]],
      mobile: ['', [mobileValidator], mobileAsyncValidator],
      passwordsGroup: fb.group({
        password: ['', [Validators.minLength(5)]],
        pconfirm: ['']
      }, {validator: this.equalValidator})
    });
  }

  equalValidator(passordsGroup: FormGroup): any{
    // const pass = passordsGroup.get('passwordsGroup').get('password');
    const password: FormControl = passordsGroup.get('password') as FormControl;
    const pconfirm: FormControl = passordsGroup.get('pconfirm') as FormControl;
    const isValid = (password.value === pconfirm.value);
    console.log('密码是否一致:' + isValid);
    return isValid ? null : {equal: {descxxx: '密码不匹配,请重新输入'}};
  }
  onSubmit(): void{
     const isValid: boolean = this.formModel.get('username').valid;
     console.log('username的校验结果: ' + isValid);
     const errors: any = this.formModel.get('username').errors;
     console.log('username的错误信息是:' + JSON.stringify(errors));
     if (this.formModel.valid){
      console.log(this.formModel.value);
    }
  }

  ngOnInit(): void {
  }

}

validators.TS

import {FormControl} from '@angular/forms';
import {of} from  'rxjs';

export function mobileValidator(control: FormControl): any {
  const myreq = /^(1(3|4|5|6|7|8|9)\d{9})$/;
  const valid = myreq.test(control.value);
  console.log('mobile的校验结果是: ' + valid);
  return valid ? null : {mobilenumber: true};
}

export function mobileAsyncValidator(control: FormControl): any {
  const myreq = /^(1(3|4|5|6|7|8|9)\d{9})$/;
  const valid = myreq.test(control.value);
  console.log('mobile的校验结果是: ' + valid);
  return of(valid ? null : {mobilenumber: true});
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值