Angular Form component class is :
export class SpecsFilterFormComponent implements OnInit {
specFilterForm: FormGroup;
cameraSizeMin = new FormControl("", [Validators.pattern("\s*|[0-9.]*")]);
cameraSizeMax = new FormControl("", [Validators.pattern("\s*|[0-9.]*")]);
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.specFilterForm = this.fb.group({
cameraSize: this.fb.group(
{
cameraSizeMin: this.cameraSizeMin,
cameraSizeMax: this.cameraSizeMax,
})
});
this.specFilterForm.valueChanges.debounceTime(500).filter(
formData => this.specFilterForm.valid)
.subscribe(
formData => {
console.log("do something after validation")
});
}
}
I want to add a validation to make sure that cameraSizeMax >= cameraSizeMin, how to apply this validation in the from control cameraSizeMin and cameraSizeMax.
To use an async validator in reactive forms, begin by injecting the validator into the constructor of the component class. Then, pass the validator function directly to the FormControl to apply it.
In simple words, making sure our data is correct by using multiple fields to check the validity of another. In fancier terms, this process is called Cross Field Validation. Sanity checking your dataset for data integrity is essential to have accurate analysis and running machine learning models.
updateValueAndValidity allows you to modify the value of one or more form controls and the flag allows you to specify if you want this to emit the value to valueChanges subscribers.
I have created a custom validator that is applied to the complete formgroup and adds then the error at the form control:
Following sets the cameraSizeMin to invalid.
class CustomValidator {
static validate(abstractForm: FormGroup): {[key: string]: any} => {
let cameraSizeMin = abstractForm.get("cameraSizeMin");
let cameraSizeMax = abstractForm.get("cameraSizeMax");
//validation logic in condition below
if (true) {
cameraSizeMin.setErrors({"customValidation": true});
}
}
}
You register it to the formGroup by:
this.specFilterForm = this.fb.group({
cameraSize: this.fb.group(
{
cameraSizeMin: this.cameraSizeMin,
cameraSizeMax: this.cameraSizeMax,
}, {validator: CustomValidator.validate}
)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With