1

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 ?

Joe Clay
  • 33,401
  • 4
  • 85
  • 85

1 Answers1

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

Working demo

Aamir Khan
  • 2,945
  • 2
  • 25
  • 32