我在Angular2中使用FormBuilder,我创建了一个自定义验证器服务。
组件
this.exampleForm = this.formBuilder.group({
'FirstName': ['', Validators.required],
'LastName': ['', [Validators.required]],
'Description': [''],
'Location': [''],
});
this.exampleForm .addControl("StartDate", this.formBuilder.group({
'Month': [0, [Validators.required, ValidationService.monthValidator]],
'Year': [0, [Validators.required, ValidationService.yearValidator]]
}));
this.exampleForm .addControl("EndDate", this.formBuilder.group({
'Month': [0],
'Year': [0]
}));
HTML组件
<div formGroupName="StartDate">
<select formControlName="Month">
<option>...</option>
</option>
</select>
<select formControlName="Year">
<option>...</option>
</select>
</div>
我不希望早于EndDate而不是StartDate
如何基于StarDate控件验证EndDate控件?
修改
尝试过这样的事情:
this.exampleForm = this.formBuilder.group({
...
}, passwordMatchValidator);
function passwordMatchValidator(g: FormGroup) {
return g.get('FirstName').value === g.get('LastName').value
? null : {'mismatch': true};
}
它没有做任何事情
答案 0 :(得分:1)
您应该在FormGroup中对两个控件进行分组,并测试此FormGroup是否有效 https://angular.io/docs/ts/latest/api/forms/index/FormGroup-class.html
修改强>
默认情况下,如果每个FormControl都有效,则表单组有效。 您可以像对FormControl一样为FormGroup定义客户验证器。 在这个例子中,我向包含两个FormControl的FormGroup添加了一个验证器(passwordMatchValidator)。
计算器-form.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder } from '@angular/forms';
@Component({
selector: 'stackoverflow-form',
templateUrl: 'stackoverflow-form.component.html',
styleUrls: [
'stackoverflow-form.component.css'
],
providers: []
})
export class StackOverflowFormComponent implements OnInit {
public myForm: FormGroup;
public alphaCtrl: FormControl;
public betaCtrl: FormControl;
constructor(fb: FormBuilder) {
this.alphaCtrl = fb.control('alphaValue', [StackOverflowFormComponent.myControlValidator]);
this.betaCtrl = fb.control('betaValue', [StackOverflowFormComponent.myControlValidator]);
this.myForm = new FormGroup({
alpha: this.alphaCtrl,
beta: this.betaCtrl,
}, StackOverflowFormComponent.passwordMatchValidator);
}
// Custom FormControl Validator
static myControlValidator(control: FormControl) {
return control.value.length > 1 ? null : { myInvalid: true};
}
// Custom FormGroup Validator
static passwordMatchValidator(g: FormGroup) {
return g.get('alpha').value === g.get('beta').value
? null : {'mismatch': true};
}
ngOnInit() {}
}
计算器-form.component.html
<form (ngSubmit)="onSubmit()" [formGroup]="myForm">
<input formControlName="alpha" name="alpha"/>
<input formControlName="beta" name="beta"/>
<button type="submit" [disabled]="!myForm.valid">SEND</button>
</form>
计算器-form.component.css
input.ng-invalid {
background-color: red;
}
input.ng-valid {
background-color: greenyellow;
}