I have a angular reactive form with input fields HTML
<form [formGroup]="ExampleForm">
<input formControlName="Key" id="Key" type="text"
[attr.aria-required]="ExampleForm.get('Key').errors ? ExampleForm.get('Key').errors.required ? 'true' : null : null"
[attr.data-invalid]="(isControlInvalid('Key')) ? 'true' : null"/>
<div>"error1"</div>
<input formControlName="Value" id="Value" type="text"
[attr.aria-required]="ExampleForm.get('Value').errors ? ExampleForm.get('Value').errors.required ? 'true' : null : null"
[attr.data-invalid]="(isControlInvalid('Value') || validateValue()) ? 'true' : null"/>
<div *ngIf = "validateValue()">"error1"</div>
<div *ngIf = "ExampleForm.get('Value').errors ? ExampleForm.get('Value').errors.required ? 'true' : null : null">"error2"</div>
I have ts file as
this.ExampleForm = this.fb.group({
Key: ["", Validators.required],
Value: ["", Validators.required]
});
validateValue() {
let key = this.ExampleForm.get("Key").value;
let value = this.ExampleForm.get("Value").value;
if ((value && value.length > 0) && (key === "Apple")) {
this.ExampleForm.get("Value").setValidators([Validators.required, Validators.pattern("^[0-9A-Za-z .-]+$")]);
return true;
}
return false;
}
I need to validate "value" field based on the text present in "key" and show error messages accordingly. with the above code both error messages pop up if the text is according to validation also..How can i achieve this?