Feel free to utilize the following code snippet:
<ion-content>
<form *ngIf="form" [formGroup]="form" (ngSubmit)="createItem()">
<ion-list>
<ion-item>
<ion-label color="primary">{{ 'EMAIL_TITLE_INPUT' | translate }}</ion-
label>
<ion-input type="email" formControlName="email"></ion-input>
</ion-item>
<ion-item class="error-message" *ngIf="hasError('email', 'emailBadFormat')">
<p text-wrap>Email is not valid</p>
</ion-item>
<ion-item>
<ion-label color="primary">{{ 'PASSWORD_TITLE_INPUT' | translate }}</ion-label>
<ion-input type="password" formControlName="password"></ion-input>
</ion-item>
<ion-item class="error-message" *ngIf="hasError('password', 'passwordBadFormat')">
<p text-wrap>Password must contain at least 1 uppercase Letter, 1 Number and must be between 4 and 12 characters long</p>
</ion-item>
</ion-list>
</form>
</ion-content>
Include this in your TypeScript file :
import {InputValidators} from "./InputValidator";
constructor(formBuilder: FormBuilder) {
this.form = formBuilder.group({
email: ['', [Validators.required, InputValidators.emailValidate()]],
password: ['', [Validators.required, InputValidators.passwordValidate()]],
phone: ['']
});
}
hasError(field: string, error: string) {
const ctrl = this.form.get(field);
return ctrl.dirty && ctrl.hasError(error);
}
Also, add the code below in InputValidator.ts:
import { AbstractControl} from "@angular/forms";
export class InputValidators {
static passwordValidate() {
return (control:AbstractControl): {[key:string] : boolean} => {
if (!control.value || 0 === control.value.length) {
return null;
}
if (/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,12}$/.test(control.value)){
return null;
}
return {"passwordBadFormat": true};
};
}
static emailValidate() {
return (control:AbstractControl): {[key:string] : boolean} => {
if (!control.value || 0 === control.value.length) {
return null;
}
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(control.value)){
return null;
}
return {"emailBadFormat": true};
};
}
}