0

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?

New123
  • 219
  • 1
  • 4
  • 13
  • 1
    It is basically the same scenario as with "password" and "repeat password" scenario. Take a look, for example. at this one: https://stackoverflow.com/questions/51605737/confirm-password-validation-in-angular-6 – Maciej Kasprzak Apr 03 '20 at 06:54
  • @MaciejKasprzak Thank you,How about doing in this method...from HTML? and im applying this logic while editing the field too – New123 Apr 03 '20 at 09:04

0 Answers0