Reputation: 3986
I am learning Ionic at the time. But it seems like HTML5 validation is not working in Ionic.
So, i have a login form like below.
<h3> Login </h3>
<form>
<input name="emailaddress" placeholder="Enter Email Address" class="email" [(ngModel)]="userData.l_email" type="email" required />
<input name="name" placeholder="Enter Password" class="name" type="password" [(ngModel)]="userData.l_password" required />
<button class="semi-transparent-button is-blue with-border" (click)="login()">
Login
</button>
</form>
When i click on login button it didn't perform validation. As i have put required in both field but it simply submit the form.
Also email validation is not working.
I have checked How can I make validation of email in Ionic using HTML5, JS or Angular work? but it is a work around. That i want to avoid.
Upvotes: 0
Views: 2407
Reputation: 1127
HTML5 form validation does not work in Ionic. Instead, you can use Angular forms.
This is a great tutorial by Josh Morony on how to do it.
In your case, you can do something like this using FormBuilder
and specifying Validators
for each field (for a full list of available validators, take a look at the docs).
import { Component } from '@angular/core';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class Login {
login: FormGroup;
submitted: boolean = false;
constructor(public formBuilder: FormBuilder) {
this.login = this.formBuilder.group({
email: ['', Validators.compose([Validators.email, Validators.required])],
password: ['', Validators.required],
});
}
onLogin() {
this.submitted = true;
if (this.login.valid) {
console.log(this.login.value);
}
}
}
In your template, use FormGroup
and show your error message when the field is invalid.
<form [formGroup]="login" (ngSubmit)="onLogin()">
<ion-item>
<ion-label>Email</ion-label>
<ion-input type="email" formControlName="email"></ion-input>
</ion-item>
<p ion-text [hidden]="login.controls.email.valid || submitted === false" color="danger" padding-left>
Please enter a valid email
</p>
<ion-item>
<ion-label>Password</ion-label>
<ion-input type="password" formControlName="password"></ion-input>
</ion-item>
<p ion-text [hidden]="login.controls.password.valid || submitted === false" color="danger" padding-left>
Password is required
</p>
<button ion-button type="submit">Login</button>
</form>
Upvotes: 3