Tonan
Tonan

Reputation: 147

Angular Reactive Form Individual Field Validation

When Validating a reactive form in Angular I want the error message to be displayed under the invalid field when an invalid data is entered.

<form  (ngSubmit)=sendQuery() [formGroup]="form">
  <div *ngFor='let key of modelKeys'>
    {{key}}
    <input name="query" placeholder="Enter {{key}} Here" formControlName="{{key}}" />
    <div *ngIf="(!key.untouched) || !(key.pristine) && !key.valid">
        Enter valid {{key}} detail
    </div>
  </div>
  <button type="submit" [disabled]='!form.valid'>Submit</button>
</form>

I always get the error messages displayed for all fields even if the field is valid. Why is the condition to display always true when the data is valid?

Output

enter image description here

Environment: Angular CLI: 7.1.3, rxjs 6.3.3, typescript 3.1.1

Upvotes: 1

Views: 973

Answers (1)

Fabian K&#252;ng
Fabian K&#252;ng

Reputation: 6183

The problem with your code is here:

<div *ngIf="(!key.untouched) || !(key.pristine) && !key.valid">
  Enter valid {{key}} detail
</div> 

key is just the (string?) key of your data and you are using it as a FormControl object, which obviously doesn't work. To use properties like untouched, pristine and valid you need to refer to a FormControl.

Here is a quick stackblitz that shows how you could solve this.

Also I think your validation does not really work the way it is implemented currently, in the stackblitz I have implemented just a dummy validation that checks for the length of the string but it showcases how it works (only showing error message for the field that is actually invalid, e.g. length is 0).

And regarding your question why your error message always shows, this is because the condition (!key.untouched) || !(key.pristine) && !key.valid will always evaluate to true if key is a string. 'myKey'.untouched will evaluate to undefined, which turns it into !undefined, which becomes true.

Upvotes: 1

Related Questions