Html 如何使用 Angular 2 / Typescript 限制输入字段中的特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45072369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to restrict special characters in the input field using Angular 2 / Typescript
提问by Bhrungarajni
I am new to Angular 2. I need to prevent special characters from being typed in the input field. If I type alphanumerics, it must accept them, while special characters should be blocked. Can anyone help please.
我是 Angular 2 的新手。我需要防止在输入字段中输入特殊字符。如果我输入字母数字,它必须接受它们,而应该阻止特殊字符。任何人都可以请帮忙。
I am sharing the code here.
我在这里分享代码。
In HTML:
在 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>
In TS:
在 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));
}
回答by Maulik Modi
You were doing everything right. Just the function needs to be changed a bit. You were using ngModelChange to bind event which is not there. You can use keypressevent handler as shown below.
你做的一切都是正确的。只是功能需要稍微改动一下。您正在使用 ngModelChange 绑定不存在的事件。您可以使用按键事件处理程序,如下所示。
HTML
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>
Component
成分
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" is the object of "$event" itself which you have passed earlier. Try this one, it will surely work with angular2.
“event”是您之前传递的“$event”本身的对象。试试这个,它肯定适用于 angular2。
回答by sivi911
I combined several answers from this and other posts and created my custom directive for handling both manual input and pasting data.
我结合了这个帖子和其他帖子的几个答案,并创建了我的自定义指令来处理手动输入和粘贴数据。
The directive:
该指令:
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();
}
}
}
Usage:
用法:
<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}">
This is actually my first stackoverflow answer so I hope it helps.
这实际上是我的第一个 stackoverflow 答案,所以我希望它有所帮助。
回答by Mohideen bin Mohammed
angular2 code sample.
angular2 代码示例。
<input type="text" pattern="/[A-Z]{5}\d{4}[A-Z]{1}/i">
or
或者
<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));
}
here is the working sample in pure javascript because angular2/typescript wont support in StackOverflow.
这是纯 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)"/>
回答by Manu A.T
You can use pattern in input tag Works fine with angular7.
您可以在输入标签中使用模式 使用 angular7 可以正常工作。
for validating special characters
用于验证特殊字符
<input #Name="ngModel" type="text" name="Name" required maxlength="256" minlength="2"
[(ngModel)]="Name" class="validate form-control" pattern="^[a-zA-Z0-9]+$">
</div>
allowing Space use => pattern="^[a-zA-Z0-9 ]+$">
允许空间使用 => pattern="^[a-zA-Z0-9 ]+$">
full usage with showing Validation Message :
显示验证消息的完整用法:
<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>
回答by N?s????? ?
You could also made used of Regex pattern
您还可以使用 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) {
}
}
回答by md imran
you can go with ng-change attribute then call function in javascript and validate there..
您可以使用 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>
In javaScript:
在 JavaScript 中:
myValidateFunction()
{
if ($scope.name.matches("^[a-zA-Z0-9]+$")) {
return true;
}
else {
return false
}
}
Based on function result you can do what you want ...validate or disallow or if you want to show any CSS msg then you can
根据函数结果,你可以做你想做的事情......验证或禁止,或者如果你想显示任何 CSS msg 那么你可以
回答by Prathmesh Dali
You can use html5 pattern validator as
您可以使用 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]">
Add novalidate to form and then you can display error for same as
将 novalidate 添加到表单中,然后您可以显示相同的错误
<div *ngIf="name?.errors.pattern && name.dirty && name.invalid">Error Message</div>