Reputation: 1056
I am using Ionic@3 searchbar in the project and we want to do input validation on it, for example min-length and some pattern matching. I understand Angular provides some input validator for validation, but these are only applicable to input type and not on ionic searchbar (though searchbar wraps a input element).
How do I do input validation on ionic searchbar ?
Upvotes: 2
Views: 2097
Reputation: 1312
Check Demo:https://stackblitz.com/edit/filter-validate-ionic-2?embed=1&file=pages/home/home.ts
In the demo, I've added a check inside of the getItems method, to check the length of
the searched value:
Upvotes: 0
Reputation: 44659
Well, since the searchbar wraps the input, you could handle those validations in the component code. Please take a look at this working plunker.
In the demo, I've added a check inside of the getItems
method, to check the length of the searched value:
// Check the length
if(val.length < 5) {
this.errorMessage = 'Please enter 5 characters at least...';
return;
}
You could also add some other validations to match a pattern, and so on. Again, I think this is the cleanest way to do it since the search bar wraps the input and trying to access to that input would be a more like a hacky solution.
View
<ion-header>
<ion-navbar>
<ion-title>
Searchbars
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-searchbar (ionInput)="getItems($event)"></ion-searchbar>
<span *ngIf="errorMessage" class="error">{{ errorMessage }}</span>
<ion-list>
<ion-item *ngFor="let item of items">
{{ item }}
</ion-item>
</ion-list>
</ion-content>
Component
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({...})
export class HomePage {
items;
errorMessage;
constructor() {
this.initializeItems();
}
initializeItems() {
this.items = [
'Amsterdam',
'Bogota',
'Buenos Aires',
'Cairo',
'Dhaka',
'Edinburgh',
'Geneva',
'Genoa',
'Glasglow',
'Hanoi',
'Hong Kong',
'Islamabad',
'Istanbul',
'Jakarta',
'Kiel',
'Kyoto',
'Le Havre',
'Lebanon',
'Lhasa',
'Lima',
'London',
'Los Angeles',
'Madrid',
'Manila',
'New York',
'Olympia',
'Oslo',
'Panama City',
'Peking',
'Philadelphia',
'San Francisco',
'Seoul',
'Taipeh',
'Tel Aviv',
'Tokio',
'Uelzen',
'Washington'
];
}
getItems(ev) {
// Reset items back to all of the items
this.initializeItems();
// set val to the value of the ev target
var val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
// Check the length
if(val.length < 5) {
this.errorMessage = 'Please enter 5 characters at least...';
return;
}
this.items = this.items.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
});
// Clear the error message
this.errorMessage = null;
}
}
}
Upvotes: 1