简体   繁体   中英

How to create directive in angular 2 that to allow text only

i have created following directive allow only numbers using key codes (when i copy text and paste in text box ,it accepting but do not accept)

is it possible to use replace and pattern to restrict numbers or text

angular 4 directive(referred from stackoverflow site)

import {Directive,HostListener,HostBinding,Input ,Renderer,ElementRef} from '@angular/core'


@Directive({
    selector: '[OnlyNumber]'
})

export class InputRestricter {

    constructor(private el: ElementRef) { }

    @Input() OnlyNumber: boolean;

    @HostListener('keydown', ['$event']) onKeyDown(event:any) {
        let e = <KeyboardEvent>event;
        if (this.OnlyNumber) {
            if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
                // Allow: Ctrl+A
                (e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
                // Allow: Ctrl+C
                (e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
                // Allow: Ctrl+V
                (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
                // Allow: Ctrl+X
                (e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
                // Allow: home, end, left, right
                (e.keyCode >= 35 && e.keyCode <= 39)) {
                // let it happen, don't do anything
                return;
            }
            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
        }
    }
}

i have created directive in angularJS using pattern and replace

app.directive('test',function(){
return{
    require:'ngModel',
    restrict :'A',
    link:function(scope,elm,attr,ngmodelctrl){
    ngmodelctrl.$parsers.push(function(val){
  //  var clean=val.replace(/^(0*)/,'');
  //var clean =val.replace(/[^0-9\.]/g,'')
  var clean =val.replace(/[^a-zA-Z\.]/g,'')
  ngmodelctrl.$setViewValue(clean);
    ngmodelctrl.$render();
    });
    }
}

})

i want 2 directives that allow only text and another to accept only numbers

If you need to validate the input to accept only numbers or text, you should use angular validation and actually you need to build your own validations. You will find a good example here.

https://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html

But if you need to force the user to enter only text, you need to listen to key and change events of the input then, once the entered value does not match your requirements you should write:

e.preventDefault();
return false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM