如何使用 Angular 2/Typescript 限制输入字段中的特殊字符

新手上路,请多包涵

我是 Angular 2 的新手。我需要防止在输入字段中输入特殊字符。如果我输入字母数字,它必须接受它们,而特殊字符应该被阻止。谁能帮忙。

我在这里分享代码。

在 HTML 中:

 <md-input-container>
   <input type="text" (ngModelChange)="omit_special_char($event)" mdInput name="name" [(ngModel)]="company.name" placeholder="Company Name" #name="ngModel" minlength="3" required>
</md-input-container>

在 TS 中:

 public e: any;

omit_special_char(val)
{
   var k;
   document.all ? k = this.e.keyCode : k = this.e.which;
   return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}

原文由 Bhrungarajni 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 442
2 个回答

你做的一切都是对的。只是功能需要稍微改变一下。您正在使用 ngModelChange 绑定不存在的事件。您可以使用 按键 事件处理程序,如下所示。

HTML

    <md-input-container>
    <input type="text" (keypress)="omit_special_char($event)" mdInput name="name" [(ngModel)]="company.name" placeholder="Company Name" #name="ngModel" minlength="3" required>
    </md-input-container>

零件

omit_special_char(event)
{
   var k;
   k = event.charCode;  //         k = event.keyCode;  (Both can be used)
   return((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}

“event”是您之前传递的“$event”本身的对象。试试这个,它肯定会与 angular2 一起工作。

原文由 Maulik Modi 发布,翻译遵循 CC BY-SA 3.0 许可协议

我结合了这个和其他帖子的几个答案,并创建了我的自定义指令来处理手动输入和粘贴数据。

指令:

 import { Directive, ElementRef, HostListener, Input } from '@angular/core';
    @Directive({
        selector: '[appInputRestriction]'
    })
    export class InputRestrictionDirective {
        inputElement: ElementRef;

        @Input('appInputRestriction') appInputRestriction: string;
        arabicRegex = '[\u0600-\u06FF]';

        constructor(el: ElementRef) {
            this.inputElement = el;
        }

        @HostListener('keypress', ['$event']) onKeyPress(event) {
            if (this.appInputRestriction === 'integer') {
                this.integerOnly(event);
            } else if (this.appInputRestriction === 'noSpecialChars') {
                this.noSpecialChars(event);
            }
        }

        integerOnly(event) {
            const e = <KeyboardEvent>event;
            if (e.key === 'Tab' || e.key === 'TAB') {
                return;
            }
            if ([46, 8, 9, 27, 13, 110].indexOf(e.keyCode) !== -1 ||
                // Allow: Ctrl+A
                (e.keyCode === 65 && e.ctrlKey === true) ||
                // Allow: Ctrl+C
                (e.keyCode === 67 && e.ctrlKey === true) ||
                // Allow: Ctrl+V
                (e.keyCode === 86 && e.ctrlKey === true) ||
                // Allow: Ctrl+X
                (e.keyCode === 88 && e.ctrlKey === true)) {
                // let it happen, don't do anything
                return;
            }
            if (['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'].indexOf(e.key) === -1) {
                e.preventDefault();
            }
        }

        noSpecialChars(event) {
            const e = <KeyboardEvent>event;
            if (e.key === 'Tab' || e.key === 'TAB') {
                return;
            }
            let k;
            k = event.keyCode;  // k = event.charCode;  (Both can be used)
            if ((k > 64 && k < 91) || (k > 96 && k < 123) || k === 8 || k === 32 || (k >= 48 && k <= 57)) {
                return;
            }
            const ch = String.fromCharCode(e.keyCode);
            const regEx = new RegExp(this.arabicRegex);
            if (regEx.test(ch)) {
                return;
            }
            e.preventDefault();
        }

        @HostListener('paste', ['$event']) onPaste(event) {
            let regex;
            if (this.appInputRestriction === 'integer') {
                regex = /[0-9]/g;
            } else if (this.appInputRestriction === 'noSpecialChars') {
                regex = /[a-zA-Z0-9\u0600-\u06FF]/g;
            }
            const e = <ClipboardEvent>event;
            const pasteData = e.clipboardData.getData('text/plain');
            let m;
            let matches = 0;
            while ((m = regex.exec(pasteData)) !== null) {
                // This is necessary to avoid infinite loops with zero-width matches
                if (m.index === regex.lastIndex) {
                    regex.lastIndex++;
                }
                // The result can be accessed through the `m`-variable.
                m.forEach((match, groupIndex) => {
                    matches++;
                });
            }
            if (matches === pasteData.length) {
                return;
            } else {
                e.preventDefault();
            }
        }

    }

用法:

 <input type="text" appInputRestriction="noSpecialChars" class="form-control-full" [(ngModel)]="noSpecialCharsModel" [ngModelOptions]="{standalone: true}" [disabled]="isSelected" required>

<input type="text" appInputRestriction="integer" class="form-control-full" [(ngModel)]="integerModel" [ngModelOptions]="{standalone: true}">

这实际上是我的第一个 stackoverflow 答案,所以我希望它能有所帮助。

原文由 sivi911 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题