如何使用angular2 / typescript限制输入字段中的特殊字符

时间:2017-07-13 05:50:45

标签: javascript html angular typescript angular2-directives

我是Angular2的新手。现在我需要限制输入字段中的特殊字符,如果我给它必须采用的数字和字母,应该阻止特殊字符。任何人都可以帮忙。

我在这里分享代码:

In 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));
}

7 个答案:

答案 0 :(得分:9)

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

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

答案 1 :(得分:8)

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

指令:

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答案,所以我希望它有所帮助。

答案 2 :(得分:1)

angular2代码示例。

<input type="text" pattern="/[A-Z]{5}\d{4}[A-Z]{1}/i">

<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(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));
}

这是纯javascript中的工作示例,因为在StackOverflow中不支持angular2 / typescript。

function omit_special_char(e) {
    var k;
    document.all ? k = e.keyCode : k = e.which;
    return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}
<input type="text" onkeypress="return omit_special_char(event)"/>

答案 3 :(得分:1)

您可以在输入标签中使用模式 与angular7搭配正常。

用于验证特殊字符

                <input #Name="ngModel" type="text" name="Name" required maxlength="256" minlength="2"
                    [(ngModel)]="Name" class="validate form-control" pattern="^[a-zA-Z0-9]+$">
                </div>

允许空间 使用=> pattern =“ ^ [a-zA-Z0-9] + $”>

完整使用并显示验证消息:

                <label for="Name" class="form-label">{{"Name" | localize}}*</label>

                <div class="input-group"><input #dashboardName="ngModel" type="text" name="Name" required maxlength="256" minlength="2"
                    [(ngModel)]="Name" class="validate form-control" pattern="^[a-zA-Z0-9 ]+$">
                </div>
                <validation-messages [formCtrl]="Name"></validation-messages>
            </div>

答案 4 :(得分:0)

您还可以使用Regex模式

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

public omit_special_char(e: any) {
    try {
        let k;
        if (/^[a-zA-Z0-9\s]*$/.test(e.key)) {
            return true;
        } else {
            e.preventDefault();
            return false;
        }
    } catch (e) {
    }
}

答案 5 :(得分:-1)

你可以使用ng-change属性然后在javascript中调用函数并在那里验证..

<md-input-container> 
<input type="text" mdInput ng-change="myValidationFunction()" name="name" placeholder="Company Name" #name="ngModel" ng-model="name" minlength="3" required>
</md-input-container>

在javaScript中:

myValidateFunction() 
{
  if ($scope.name.matches("^[a-zA-Z0-9]+$")) {
     return true;
  } 
  else {
     return false
  }
}

根据功能结果,您可以执行您想要的操作...验证或禁止,或者如果您想显示任何CSS信息,那么您可以

答案 6 :(得分:-1)

您可以使用html5模式验证器作为

<input type="text" (ngModelChange)="omit_special_char($event)" mdInput name="name" [(ngModel)]="company.name" placeholder="Company Name" #name="ngModel" minlength="3" required pattern="[a-zA-Z0-9]">

向表单添加novalidate,然后您可以显示与

相同的错误
<div *ngIf="name?.errors.pattern && name.dirty && name.invalid">Error Message</div>