验证一个角反应形式的输入字段,取决于另一个值

时间:2020-04-03 06:50:40

标签: angular typescript validation angular-reactive-forms

我有一个带输入场的角反应形式 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>

我有ts文件

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;
    }

我需要根据“键”中显示的文本来验证“值”字段,并相应地显示错误消息。 使用上面的代码,如果文本也符合验证,则会弹出两个错误消息。如何实现此目的?

0 个答案:

没有答案