2017-08-25 51 views
1

我在項目中使用Ionic @ 3搜索欄,我們希望對它進行輸入驗證,例如最小長度和一些模式匹配。 我知道Angular爲驗證提供了一些輸入驗證器,但這些僅適用於輸入類型,而不適用於離子搜索欄(儘管搜索欄包含輸入元素)。在離子搜索欄上輸入驗證?

如何在離子搜索欄上進行輸入驗證?

回答

0

那麼,由於搜索欄包裝輸入,你可以在組件代碼中處理這些驗證。請看看this working plunker

在演示中,我添加了一個檢查getItems方法裏面,以檢查搜索值的長度:

// Check the length 
if(val.length < 5) { 
    this.errorMessage = 'Please enter 5 characters at least...'; 
    return; 
} 

你也可以添加一些其他的驗證匹配模式,等等上。 再次,我認爲這是最乾淨的方法,因爲搜索欄包裝輸入並試圖訪問該輸入將更像是一個hacky解決方案

查看

<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> 

組件

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; 

    } 
    } 
}