The validators you have used so far are FormControl
-validators. They validate a single FormControl
. You can also write yourself a validator that validates a FormArray
or a FormGroup
.
A validator would look something like this:
dateOrderValidator(formGroup: FormGroup): ValidationErrors | null {
const startDate = formGroup.controls['startDate']?.value;
const endDate = formGroup.controls['endDate']?.value;
// validate date-strings
// catch missing values
if (Date.parse(startDate).getTime() >= Date.parse(endDate).getTime)) {
// return an appropriate error
}
}
FormBuilder
FormBuilder's main purpose is to save us some boilerplate. Instead of
name: new FormControl(...)
we can just write
name: ['initialValue', [<synchronous validators>], [<asynchronous validators]]
or even less (if we have no validators):
name: 'initialValue'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…