I was developing a test application and had one problem with validation. I have created form and binded it with FormGroup object:
<form [formGroup]="form" (ngSubmit)="addOrEditSensor()">
<div class="block">
<p
[ngClass]="((name.errors?.required && name.touched) || (name.errors?.maxlength)) ? 'error' : 'error hidden'"
>
Fill this field. Length should be less then 30 symbols
</p>
<div class="input-block">
<label class="label" for="name">Name</label>
<input class="input_text" id="name" type="text" placeholder="Name" formControlName="name">
</div>
</div>
...
private fillForm(){
this.form = new FormGroup({
id: new FormControl(this.sensor.id),
name: new FormControl(this.sensor.name, [Validators.required, Validators.maxLength(30)]),
model: new FormControl(this.sensor.model, [Validators.required, Validators.maxLength(15)]),
range_from: new FormControl(this.sensor.range_from, [Validators.required]),
range_to: new FormControl(this.sensor.range_to, [Validators.required]),
type: new FormControl(this.sensor.type, [Validators.required]),
unit: new FormControl(this.sensor.unit, [Validators.required]),
location: new FormControl(this.sensor.location, [Validators.required, Validators.maxLength(40)]),
description: new FormControl(this.sensor.description, [Validators.required, Validators.maxLength(200)])
})
}
All standart validation works correctly, like that:
And now i got a new task. I have number inputs 'range from' and 'range to' and i have to create a custom validator, which checks if from less then to. So i created a custom function and added this validator:
checkRange(control: FormControl){
if (control.value >= this.form.value.range_to){
return {invalidRange: true}
}
return null
}
range_from: new FormControl(this.sensor.range_from, [Validators.required, this.checkRange])
And after that my modal breaks and I got a lot of errors and my form is undefined: