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 ?
-
There is no such thing as angular JS 2Aamir Khan– Aamir Khan2017-11-15 11:33:10 +00:00Commented Nov 15, 2017 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– Joe Clay2017-11-15 11:34:17 +00:00Commented Nov 15, 2017 at 11:34
-
@AamirKhan Yes I am using Angular version 2.0user8944795– user89447952017-11-15 11:41:03 +00:00Commented Nov 15, 2017 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: stackoverflow.com/a/3809435/2227788Aamir Khan– Aamir Khan2017-11-15 11:43:19 +00:00Commented Nov 15, 2017 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 commentsuser8944795– user89447952017-11-15 12:03:15 +00:00Commented Nov 15, 2017 at 12:03
|
Show 4 more comments
1 Answer
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" />