How can I set the minTemperature error for the temperature form control in a custom validator within this form group? I want it to be marked as invalid when the value is less than 26 degrees Celsius or less than 80 degrees Fahrenheit, based on the selected unit.
Custom Validator
getTemperatureAndUnitValidator(): ValidatorFn {
return (form: FormGroup): { [key: string]: any } => {
const temperatureControl = form.controls['temperature'];
const selectedTemperatureControl = form.controls['temperatureUnit'];
const temperature = temperatureControl.value;
if (selectedTemperatureControl.value.code === 'F' && temperature < 80) {
return { minTemperature: true };
} else if (
selectedTemperatureControl.value.code === 'C' &&
temperature < 26
) {
return { minTemperature: true };
}
return null;
};
}
Form Group
this.heatIndexForm = new FormGroup(
{
temperature: new FormControl(null, [
Validators.required,
Validators.pattern(/^-?[0-9]\d*(\.\d+)?$/),
]),
humidity: new FormControl(null, [
Validators.required,
Validators.min(0),
Validators.max(100),
Validators.pattern(/^-?[0-9]\d*(\.\d+)?$/),
]),
temperatureUnit: new FormControl(new Temperature('Celsius', 'C')),
},
{ validators: this.heatIndexService.getTemperatureAndUnitValidator() }
);
Validation Error in HTML
<div class="validation-error"
*ngIf="temperatureUnit.value.code === 'F' &&
heatIndexForm.get('temperature').hasError('minTemperature') &&
heatIndexForm.controls['temperature'].dirty &&
heatIndexForm.controls['temperature'].value">
Temperature must be 80°F or higher!
</div>
<div class="validation-error"
*ngIf="temperatureUnit.value.code === 'C' &&
heatIndexForm.controls['temperature'].hasError('minTemperature') &&
heatIndexForm.controls['temperature'].dirty &&
heatIndexForm.controls['temperature'].value">
Temperature must be 26°C or higher!
</div>
I attempted to implement this in the custom validator but it's not functioning correctly. The validation error isn't being triggered in the template and the input isn't displaying a red border. I am using pInputText which has a built-in red border that should apply when the input is invalid.
return {temperatureControl: { minTemperature: true }}
I prefer not to use .setErrors.