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 ?

9
  • There is no such thing as angular JS 2 Commented Nov 15, 2017 at 11:33
  • 1
    To 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). Commented Nov 15, 2017 at 11:34
  • @AamirKhan Yes I am using Angular version 2.0 Commented 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/2227788 Commented 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 comments Commented Nov 15, 2017 at 12:03

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.