(十七)、Angular4.0 响应式表单校验

一、在app下新建validator目录,创建一个ValidatorScript的ts类型文件,用来编写检验方法

import {FormControl, FormGroup} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/delay';

// 手机号码校验
export function mobileVlidator(control: FormControl): any {
  const  myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;

  const valid = myreg.test(control.value);
  console.log('mobile的校验结果' + valid);

  return valid ? null : {mobile: true};
}

// 手机号码异步校验
export function mobileAsyncVlidator(control: FormControl): any {
  const  myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;

  const valid = myreg.test(control.value);
  console.log('mobile的校验结果' + valid);

  return Observable.of(valid ? null : {mobile: true}).delay(5000);
}

// 确认密码验证
export function equalsValidator(group: FormGroup): any {
  const password: FormControl = group.get('password') as FormControl;
  const pConfirm: FormControl = group.get('pConfirm') as FormControl;
  const valid: boolean = (password.value === pConfirm.value);
  console.log('密码校验结果' + valid);
  return valid ? null : {equals: true};
}

二、修改reactive-regist.component.ts,添加校验

import { Component, OnInit } from '@angular/core';
import {AbstractControl, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {equalsValidator, mobileAsyncVlidator, mobileVlidator} from '../validator/ValidatorScript';

@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: ['', [Validators.required, Validators.minLength(6)]],
      mobile  : ['', mobileVlidator, mobileAsyncVlidator],
      passwordsGroup: fb.group({
        password: ['', [Validators.minLength(6)]],
        pConfirm: ['']
      }, {validator: equalsValidator})
   });
  }

  // 响应式表单校验
  validateForm(control: AbstractControl): {[key: string]: any} {
    return null;
  }

  onSubmit() {
    // const isVaild = this.formModel.get('username').valid;
    // console.log('username校验结果为: ' + isVaild);
    if (this.formModel.valid) {
      console.log(this.formModel.value);
    }
  }

  ngOnInit() {
  }

}

三、reactive-regist.component.html

<form [formGroup]="formModel" (submit)="onSubmit()">
  <div>用户名:<input type="text" formControlName="username"></div>
  <div [hidden]="!formModel.hasError('required','username')">
    用户名不能为空
  </div>
  <div [hidden]="!formModel.hasError('minlength','username')">
    用户名最小长度是6
  </div>
  <div>手机号:<input type="text" formControlName="mobile"></div>
  <div [hidden]="!formModel.hasError('mobile','mobile')">
    请输入正确的手机号
  </div>
  <div formGroupName="passwordsGroup">
    <div>密码:<input type="password" formControlName="password"></div>
    <div [hidden]="!formModel.hasError('minlength',['passwordsGroup','password'])">
      密码最小长度是6
    </div>
    <div>确认密码:<input type="password" formControlName="pConfirm"></div>
    <div [hidden]="!formModel.hasError('equals','passwordsGroup')">
      密码不匹配
    </div>
  </div>
  <button type="submit">提交</button>
  <br>
  {{formModel.status}}
</form>

四、访问localhost:4200测试

五、状态字段

  • touched和untouched 是否获取焦点 示例:(把用户名的两个校验用一个div包含起来,鼠标失去焦点后显示)
  <div [hidden]="formModel.get('username').valid || formModel.get('username').untouched">
    <div [hidden]="!formModel.hasError('required','username')">
      用户名不能为空
    </div>
    <div [hidden]="!formModel.hasError('minlength','username')">
      用户名最小长度是6
    </div>
  </div>
  • pristine和dirty (如果字段的值改变过,则pristine为false,dirty为true) (把手机号的校验用一个div包含起来,鼠标失去焦点后不显示,只有在输入字符后才有校验提示)
  <div [hidden]="formModel.get('mobile').valid || formModel.get('mobile').pristine">
    <div [hidden]="!formModel.hasError('mobile','mobile')">
      请输入正确的手机号
    </div>
  </div>

  • pending,当一个字段处于异步校验时,属性为true,这个时候可以显示一段文字或图片,来告诉用户正在校验(在手机号码验证下面添加一个div,用于peding示例)
  <div [hidden]="!formModel.get('mobile').pending">
    校验手机号码中...
  </div>


六、

七、

八、

九、

十、

十一、

十二、

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值