Angular2笔记4-Form验证

在ng2 form中两个基本的对象是Control 和 ControlGroup.
一个Control代表着一个input字段(这是一个ng2表单的最小单位)
Control 封装了该字段的值,状态..

Control和ControlGroup

1
<input type="text" ng-control="name" />
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// create a new Control with the value "Nate"
var nameControl = new Control("Nate");
var name = nameControl.value; // -> Nate
// now we can query this control for certain values:
nameControl.errors // -> StringMap<string, any> of errors
nameControl.dirty // -> false
nameControl.valid // -> true
var personInfo = new ControlGroup({
firstName: new Control("Nate"),
lastName: new Control("Murray"),
zip: new Control("90210")
})
// now we can query this control group for certain values, which have sensible
personInfo.value;
// -> {
// firstName: "Nate",
// lastName: "Murray",
// zip: "90210"
// }
// values depending on the children Control's values:
personInfo.errors // -> StringMap<string, any> of errors
personInfo.dirty // -> false
personInfo.valid // -> true

最简单的form

1
2
//引入导出的类
import {DemoFormSkuBuilder} from './forms/demo_form_sku_with_builder';
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Component({
selector: 'demo-form-sku',
template: `
<div class="ui raised segment">
<h2 class="ui header">Demo Form: Sku</h2>
<form #f="ngForm" (ngSubmit)="onSubmit(f.value)" class="ui form">
<div class="field">
<label for="skuInput">SKU</label>
<input type="text" id="skuInput" placeholder="SKU" name="sku" ngModel>
</div>
<button type="submit" class="ui button">Submit</button>
</form>
</div>
`
})
export class DemoFormSku {
onSubmit(form: any): void {
console.log('you submitted value:', form);
}
}

自定义验证form

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
function skuValidator(control: FormControl): { [s: string]: boolean } {
if (!control.value.match(/^123/)) {
return {invalidSku: true};//新增的error类型
}
}
// sku 相当于是一个new Control("");
//sku.errors, sku.dirty, sku.valid 这些Control的属性
//用*ngIf控制UI
@Component({
selector: 'demo-form-with-custom-validations',
directives: [FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES],
template: `
<div class="ui raised segment">
<h2 class="ui header">Demo Form: with custom validations</h2>
<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)" class="ui form">
<div class="field" [class.error]="!sku.valid && sku.touched">
<label for="skuInput">SKU</label>
<input type="text"
id="skuInput"
placeholder="SKU"
[formControl]="sku">
<div *ngIf="!sku.valid" class="ui error message">SKU is invalid</div>
<div *ngIf="sku.hasError('required')" class="ui error message">SKU is required</div>
<div *ngIf="sku.hasError('invalidSku')" class="ui error message">SKU must begin with <tt>123</tt></div>
</div>
<div *ngIf="!myForm.valid" class="ui error message">Form is invalid</div>
<button type="submit" class="ui button">Submit</button>
</form>
</div>
`
})
export class DemoFormWithCustomValidations {
myForm: FormGroup;//表单里[formGroup]="myForm"
sku: AbstractControl;
constructor(fb: FormBuilder) {
//Form默认是一个ControlGroup
this.myForm = fb.group({
//[formControl]="sku"
//赋值可以用'sku':['ABC123']
//Validators.compose用于追加一个验证, 不然'sku': ['', Validators.required]只会保留一个
'sku': ['', Validators.compose([Validators.required, skuValidator])]
});
this.sku = this.myForm.controls['sku'];
//监听值的变化事件
this.sku.valueChanges.subscribe(
(value: string) => {
console.log('sku changed to:', value);
}
);
this.myForm.valueChanges.subscribe(
(form: any) => {
console.log('form changed to:', form);
}
);
}
onSubmit(value: string): void {
console.log('you submitted value: ', value);
}
}