The min
, max
and required
validators can be kept as is. If you want to validate one control based on the value of another, you need to lift the validation to the parent control.
import { Component } from '@angular/core';
import { ValidatorFn, FormBuilder, FormGroup, Validators } from '@angular/forms';
const portStartEnd: ValidatorFn = (fg: FormGroup) => {
const start = fg.get('portStart').value;
const end = fg.get('portEnd').value;
return start && end && start < end ? null : { startEnd: true };
}
@Component({
selector: 'my-app',
template: `
<input [formControl]="form.get('portStart')" type="number" >
<input [formControl]="form.get('portEnd')" type="number" >
{{ form.valid }}
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
portStart: [null, [Validators.required, Validators.min(0), Validators.max(65535)]],
portEnd: [null, [Validators.required, Validators.min(0), Validators.max(65535)]]
}, { validator: portStartEnd } );
}
}