I'm writing an angular 8 web application with angular material and forms.
I created a FormGroup
with FormBuilder
and added validations to the fields.
I have a field with Validators.min(0)
. the thing is that this field is not mandatory, so I want to validate that the value is minimum zero only if there is a value there to begin with.
how do I achieve that ?
ahhm.. ok this is how I built the form
this.queryForm = this.formBuilder.group({
...
durationLongerThenInSec: ['', Validators.min(0)],
});
}
thanks!
Since you do not have Validators.required
the required validation will not be applied to your form control.
You should try to add Validators.min(0)
to form control and it will validate if it's dirty and satisfies the min value rule:
this.queryForm = this.formBuilder.group({
...
durationLongerThenInSec: ['', [Validators.min(0)]],
});
}
Also make sure that you have the error display on template to handle and show error message when durationLongerThenInSec.errors.min
is available:
<p *ngIf="durationLongerThenInSec.errors?.min">error message</p>