5

I have implemented the directive to restrict the input field using angular2. It is working fine in desktop browser, but not working in android mobile.

component

import { LimitToDirective } from '../../../directives/limitedvalidation';
@Component({
  templateUrl: 'build/pages/profile/change-basic-details/change-basic-details.html',
  directives: [LimitToDirective]  
})
export class UpdateBasicDetailsPage {
  constructor(){}
}

directive

 import {Directive, Input} from '@angular/core'
    @Directive({
      selector: '[limit-to]',
      host: {
        '(keypress)': '_onKeypress($event)',
      }
    })
    export class LimitToDirective {
      @Input('limit-to') limitTo; 
      _onKeypress(e) {
         const limit = +this.limitTo;
         if (e.target.value.length === limit) e.preventDefault();
      }
    }

template

<ion-input limit-to="12" type="tel" [formControl]="aadhaarno">

3 Answers 3

8

Use maxlength as belows :

<ion-input [maxlength]="12" type="tel" [formControl]="aadhaarno">
Sign up to request clarification or add additional context in comments.

2 Comments

i am getting error in android mobile, [INFO:CONSOLE(463)] "Error: Uncaught (in promise): EXCEPTION: Error in build/pages/profile/change-basic-details/change-basic-details.html:63:8 ORIGINAL EXCEPTION: Invalid integer literal when parsing null in base 10
Oh 'cmon this only validates user input — it does not restrict user to enter more than 12 symbols in input field.
3

you should use max-length html5 attribute and then use form validation for Angular2, no custom directive needed.

3 Comments

Oh 'cmon this only validates user input — it does not restrict user to enter more than 12 symbols in input field.
can't we go and change the maxlenght limit in browser , its not safe I suppose. We need to put some validation on javascript side as well
Attention, the HTML attribute is called maxlength, not max-length, and has existed long before HTML 5...
0

Please refer

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

@Directive({
 selector: '[limit-to]',
 host: {
'(input)': 'onInputChange($event)',
}
})
export class LimitToDirective {
 @Input('limit-to') limitTo;
 @Output() ngModelChange: EventEmitter<any> = new EventEmitter();
 oldValue: any;

 onInputChange(e) {
debugger
const limit = +this.limitTo;
if (e.target.value.length > limit) {
  e.target.value = this.oldValue;
}
this.oldValue = e.target.value;
this.ngModelChange.emit(e.target.value);
}
}


<ion-input limit-to="12" type="tel" [formControl]="aadhaarno">

click

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.