我正在使用Angular 2,我想限制用户在文本框中输入URL和链接。 我们可以使用正则表达式吗?
答案 0 :(得分:0)
您可以使用指令监视文本框中的输入。该指令可以使用正则表达式来检查当前输入是否是URL。这是一个例子
import { Directive, HostListener, ElementRef } from '@angular/core';
@Directive({
selector: '[appUrlBlocker]'
})
export class UrlBlockerDirective {
constructor(private el: ElementRef) {}
expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
regex = new RegExp(this.expression);
@HostListener('keyup') check() {
if (this.el.nativeElement.value.match(this.regex)) {
alert('You have entered a URL!');
// Remove entered content
this.el.nativeElement.value = '';
} else {
console.log('Does not match');
}
}
}
然后在输入中使用它
<input appUrlBlocker type="text" placeholder="No URLs allowed" />