I am using Angular 2 and I want to restrict the user from entering URLs and links in the text box. Can we use regular expression for this ?
Asked
Active
Viewed 798 times
1
-
There is no such thing as angular JS 2 – Aamir Khan Nov 15 '17 at 11:33
-
1To clarify @AamirKhan's comment - AngularJS refers to version 1.x, Angular refers to version 2.x and above (yes, it's a confusing naming convention). – Joe Clay Nov 15 '17 at 11:34
-
@AamirKhan Yes I am using Angular version 2.0 – Nov 15 '17 at 11:41
-
You can use a directive that checks any input for being a URL. You can use a regex for this. Check out: https://stackoverflow.com/a/3809435/2227788 – Aamir Khan Nov 15 '17 at 11:43
-
@AamirKhan I have used this pattern="[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)" but still itis taking all the comments – Nov 15 '17 at 12:03
-
Check my answer. – Aamir Khan Nov 15 '17 at 12:37
-
@AamirKhan Thanks Dude, Now its working – Nov 15 '17 at 13:14
-
@debashishdwivedi You're welcome. If my answer has resolved your question then please mark it as accepted. – Aamir Khan Nov 15 '17 at 13:50
-
@AamirKhan Actually I have only 1 Reputation so I cant do that – Nov 15 '17 at 14:12
1 Answers
1
You can use a directive to monitor the input in your textbox. The directive can use a Regular Expression to check if the current input is a URL or not. Here's an example
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');
}
}
}
And then use it on your input like so
<input appUrlBlocker type="text" placeholder="No URLs allowed" />

Aamir Khan
- 2,945
- 2
- 25
- 32