(1)响应式表单验证
实现效果:
实现代码地址:https://github.com/windcat121/formA.git
(2)模板驱动表单验证
实现效果
代码如下:
html
<form nz-form>
<nz-form-item>
<nz-form-label nzRequired [nzSpan]="5">用户名</nz-form-label>
<nz-form-control [nzSpan]="12">
<input #unameValid="ngModel" nz-input required name="uname" [(ngModel)]="this.info.username" nz-tooltip nzTitle="请输入用户姓名" placeholder="请输入用户姓名hh" autocomplete="off" />
<nz-form-explain *ngIf="unameValid.invalid&&unameValid.dirty&&unameValid.errors.required">
必填项不能为空!
</nz-form-explain>
</nz-form-control>
</nz-form-item>
<nz-form-item>
<nz-form-label [nzSpan]="5">QQ邮箱</nz-form-label>
<nz-form-control [nzSpan]="12">
<input #mailValid="ngModel" nz-input [(ngModel)]="this.info.qqmail" name="mail" pattern="\d{10}@qq.com" nz-tooltip nzTitle="请输入QQ邮箱" placeholder="请输入正确的QQ邮箱" autocomplete="off" />
<nz-form-explain *ngIf="mailValid.invalid&&mailValid.dirty&&mailValid.errors.pattern">
邮箱格式输入不正确!
</nz-form-explain>
</nz-form-control>
</nz-form-item>
<nz-form-item>
<nz-form-label [nzSpan]="5">联系方式</nz-form-label>
<nz-form-control [nzSpan]="12">
<input #phoneValid="ngModel" nz-input [(ngModel)]="this.info.phonenum" name="phone" minlength='7' maxlength='11' nz-tooltip nzTitle="请输入联系方式(7-11位)" placeholder="请输入7-11位联系方式" autocomplete="off" />
<nz-form-explain *ngIf="phoneValid.invalid&&phoneValid.dirty&&phoneValid.errors.minlength">
不能小于7位!
</nz-form-explain>
<nz-form-explain *ngIf="phoneValid.invalid&&phoneValid.dirty&&phoneValid.errors.maxlength">
不能大于11位!
</nz-form-explain>
</nz-form-control>
</nz-form-item>
</form>
<button nz-button nzType="primary" [disabled]="unameValid.invalid||mailValid.invalid||phoneValid.invalid" (click)="ok()">确定</button>
样式:
nz-form-explain
color: red
业务逻辑ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.styl']
})
export class LoginComponent implements OnInit {
info: any;
constructor() { }
ngOnInit() {
this.initListMyForm();
}
initListMyForm() {
this.info = {
username: 'sss',
qqmail: '',
phonenum: ''
};
}
ok() {
console.log('username:' + this.info.username);
console.log('qqmail:' + this.info.qqmail);
console.log('phonenum:' + this.info.phonenum);
}
}
module.ts里引入:
其他:
①在表单里,对input使用ngModel双向绑定,必须使用name属性
②如果不想使用name属性
关于表单:
input不让输入框自动填充:设置autocomplete=“off”
表单验证总结
响应式表单复用性更强