How to set maxlength for a string on ion-searchbar

I am using an ion-searchbar and want to restrict the length of a string that can be entered. I have tried the maxlength which works for the ion-input, how can we do the same for the filter?

Thanks in advance!

Maybe what you can do is build a custom directive as follows:

import { Directive, Input, HostListener } from '@angular/core';

/*
  Generated class for the LimitTo directive.

  See https://angular.io/docs/ts/latest/api/core/index/DirectiveMetadata-class.html
  for more info on Angular 2 Directives.
*/
@Directive({
  selector: '[limit-to]' // Attribute selector
})
export class LimitTo {

  @Input('limit-to') limitTo;

  constructor() {

  }
  //HostListener decorator handle event handlers for input (onKeyPress)
  @HostListener('keypress', ['$event'])
  onkeypress(ev) {
    const limit = +this.limitTo; //convert to number
    // once it reaches the limit set, stop propgating event.
    if (ev.target.value.length === limit) {
      ev.preventDefault();
    }
  }
}

import in the declarations array in app.module. Then you can use it in the html component for example to limit the number of characters to 8 as follows:

<ion-searchbar [limit-to]='8' (ionInput)="getItems($event)"></ion-searchbar>

See if it works.

Maybe you can try using the ionInput event the same way. But the advantage with a directive is that once you have build it, it is reusable across your application.

Ashley

5 Likes

Hi ashley_shookhye,

It worked :+1: Thanks

Great, thankyou very much, yes works perfectly!

I’d imagine copy/pasting would defy this. Along with doing ev.preventDefault(), I’d set the value of the input to be substr(0, limit) as well as listening to some other events, I don’t believe keypress gets activated by a paste.

Hi,

Can you show your solution?

Ashley

Solution for this is check in input type is copy paste then substring it and set the new value in ngModel

HTML Code

<ion-searchbar [limit-to]=‘8’ placeholder=“Search…” showCancelButton color=“primary” [animated]=“true” (ionInput)=“onInput($event)” [(ngModel)]=“newVal”>

Angular Code

onInput(e) {
if (e.inputType == ‘insertFromPaste’) {
this.newVal= e.target.value.substring(0, 10);
}
}

it is working fine in browser but not working in mobile