I'm starting to use Angular Reactive Forms.
I really like the idea of being able to have async validator(for things that have to check something against the DB), and I like the idea that the GUI doesn't need to know every rule.
So I've a dummy login form:
loginForm = this.formBuilder.group({
email: new FormControl(
'',
Validators.compose([Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')])
),
password: new FormControl(
'',
Validators.compose([Validators.required, Validators.minLength(8)]
)),
});
and the matching view:
<form class="ion-margin" [formGroup]="loginForm" (ngSubmit)="login()">
<ion-item lines="none">
<ion-label position="floating">Email</ion-label>
<ion-input type="text" formControlName="email"></ion-input>
</ion-item>
<ion-item lines="none">
<ion-label position="floating">Password</ion-label>
<ion-input type="password" formControlName="password"></ion-input>
</ion-item>
<ion-row class="ion-margin">
<ion-button type="submit" color="success" expand="block" [disabled]="loginForm.dirty && !loginForm.valid">Sign in</ion-button>
</ion-row>
</form>
Currently, I've no visual clue why the user cannot submit the form. Previously I was doing some ASP.Net Core projects, and there was the same kind of approach to have the model and its validations rules declared on the ViewModel/Controller side.
.ts
file? I mean, it's kind of weird that the ViewModel AND the View has to know about each error(and its parameters(like minlength)) Would it not be the responsability of the Validator to provide an error if one?Sorry for the 3 questions in one, but it was with the same example and very close.
The way I handle multiple validation messages in my ionic apps..
<ion-item>
<ion-label position="floating">Email</ion-label>
<ion-input type="text" formControlName="email"></ion-input>
</ion-item>
<div *ngFor="let validation of validation_messages.email">
<div class="error-message" *ngIf="loginForm.get('email').hasError(validation.type) && (loginForm.get('email').touched || loginForm.get('email').dirty)">
{{ validation.message }}
</div>
</div>
In the Controller file configure this as per your fields and validations.
this.validation_messages = {
'email': [
{ type: 'required', message: 'Email is required' }
],
'password': [
{ type: 'pattern', message: 'Password does not match pattern' }
]
};
This method will take care of multiple validation messages on a single field.
lines="none"
from your ion-item