Triggering field validation errors programatically


#1

Hi, I am building this login form that validates against a rest api. Upon any field validation error, this api will return a dictionary containing the field names as keys and a list of the errors for each of those keys. For example, for this form:

<form [formGroup]="form">
      <ion-row>
        <ion-col>
          <ion-list inset>
            
            <ion-item>
              <ion-input  type="text" placeholder="Email" formControlName="username" ></ion-input>
            </ion-item>
            <ion-item>
              <ion-input type="password" placeholder="Password" formControlName="password" ></ion-input>
            </ion-item>
            
          </ion-list>
        </ion-col>
      </ion-row>
      
      <ion-row>
        <ion-col class="signup-col">
          <button ion-button class="submit-btn" full type="submit" (click)="login()">Login</button>
          <button ion-button class="register-btn" block clear (click)="createAccount()">Create New Account</button>
        </ion-col>
      </ion-row>
      
    </form>

The webserver could return this json (I just made this up, don’t take the example too seriously):

{
    "username": [
        "Username not found."
    ],
    "password": [
        "Wrong password."
    ]
}

Now, I have a background developing angular applications and know that in angular, you can build asynchronous validatiors to validate individual fields against the server, but this is not useful in my case cause this webserver does not validate fields separately. And in some angular projects that i made in the past, I was able to solve this using the setErrors method:

for(var key in serverResponse["errors"]) { 

    this.form.controls[key].setErrors({serverValidationError: true});

}

This would fire all the css classes that highlight the field errors in the form, but in ionic this doesn’t seem to have any effect. So, is this not correct in ionic? What’s the approach to do this type of server side validation in ionic? I feel like it’s a very common use case but haven’t been able to find an example that covers this.


#2

Ok, I found a solution. This seems to work by checking the validity of the field in the template:

...
            <ion-item [ngClass]="{'ng-touched ng-invalid':form.controls['username'].invalid}">
              <ion-input  type="text" placeholder="Email" formControlName="username" ></ion-input>
            </ion-item>
...

So, setErrors mark the field as invalid, and then the template looks for that flag to add the css class. Not sure why this isn’t required in plain angular apps but whatever…