响应式表单校验(angular自带校验和自定义校验规则)
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormControl, FormGroup } from '@angular/forms';
import { fbind } from 'q';
@Component({
selector: 'app-form5',
templateUrl: './form5.component.html',
styleUrls: ['./form5.component.css']
})
export class Form5Component implements OnInit {
constructor(private fb: FormBuilder) { }
formModel = this.fb.group({
username: ['', [
Validators.required,
Validators.minLength(6)
]],
mobile: ['', this.mobileValidator],
passwordsGroup: this.fb.group({
password: [''],
pconfirm: ['']
}, {
validator: this.equalValidator
})
});
// 自定义校验器
/**
* control: 参数类型可以为:FormGroup,FormControl,FormArray,返回一个对象
* xxx(control: AbstractControl): {[key: string]: any} {
* return null;
* }
*/
// 验证手机号——单一字段
mobileValidator(control: FormControl): any {
const regs = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/;
const valid = regs.test(control.value);
console.log('mobile的校验结果是:' , valid);
return valid ? null : {mobile: true};
}
// 校验确认密码——同时校验几个字段
equalValidator(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 : {equal: true};
}
ngOnInit() {
}
onSubmit() {
// 获取校验信息
const info = this.formModel.get('username');
console.log('校验信息' , info);
// 获取校验结果
const isValide = this.formModel.get('username').valid;
console.log('校验结果' , isValide);
// 获取错误信息
const error = this.formModel.get('username').errors;
console.log('错误信息' , error);
// 只有当formModel中所有的字段都是合法条件
if (this.formModel.valid) {
console.log(this.formModel.value);
}
}
}
<form [formGroup]="formModel" (ngSubmit)="onSubmit()">
<div>
用户名:<input type="text" formControlName="username">
</div>
<div>
手机号:<input type="number" formControlName="mobile">
</div>
<div formGroupName="passwordsGroup">
<div>
密码:<input type="password" formControlName="password">
</div>
<div>
确认密码:<input type="password" formControlName="pconfirm">
</div>
</div>
<button>注册</button>
</form>
将自定义校验规则抽离到单独的文件
例如:validator/validators.ts
import { FormControl, FormGroup } from '@angular/forms';
// 验证手机号——单一字段
export function mobileValidator(control: FormControl): any {
const regs = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/;
const valid = regs.test(control.value);
console.log('mobile的校验结果是:' , valid);
return valid ? null : {mobile: true};
}
// 校验确认密码——同时校验几个字段
export function equalValidator(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 : {equal: {descxxx: '密码和确认密码不匹配'}};
}
使用:form5.component.ts
import { mobileValidator, equalValidator } from 'src/app/validator/validators';
constructor(private fb: FormBuilder) { }
formModel = this.fb.group({
username: ['', [
Validators.required,
Validators.minLength(6)
]],
mobile: ['', mobileValidator],
passwordsGroup: this.fb.group({
password: [''],
pconfirm: ['']
}, {
validator: equalValidator
})
});
html:
<form [formGroup]="formModel" (ngSubmit)="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="number" 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('equal', 'passwordsGroup')">
{{formModel.getError('equal', 'passwordsGroup') ?.descxxx}}
</div>
</div>
<button>注册</button>
</form>
异步校验器
在formControl的第三个参数调用。
// 异步校验器
export function mobileAsyncValidator(control: FormControl): any {
const regs = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/;
const valid = regs.test(control.value);
console.log('mobile的校验结果是:' , valid);
return Observable.of(valid ? null : {mobile: true}).delay(5000);
}