模板式表单验证

HTML

<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm.value, myForm.valid)" novalidate>
  <div>用户名:<input type="text" ngModel required minlength="6" name="username"></div>
  <div [hidden]="!myForm.form.hasError('required','username')">
    用户名是必填项
  </div>
  <div>手机号码:<input type="number" ngModel mobileValidator name="mobile"></div>
  <div ngModelGroup="passwordsGroup" appEqualValidator>
    <div>密码:<input type="password" ngModel minlength="6" name="password"></div>
    <div>确认密码:<input type="password" ngModel name="pconfirm"></div>
    <div [hidden]="myForm.hasError('equal','passwordsGroup')">
      <p >{{myForm.getError('equal','passwordsGroup')?.descxxx}}</p>
    </div>
  </div>
  <button type="submit">注册</button>
</form>

TS

import {FormControl, FormGroup} from '@angular/forms';
// tslint:disable-next-line:import-spacing
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});
}

export function 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: '密码不匹配,请重新输入'}};
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值