Utilizing span elements to display error messages

Currently, I am using a directive on a field to prevent users from entering HTML tags and JavaScript events. However, I am encountering a few challenges:

a) My goal is to display an error message immediately when a user tries to input HTML tags or JavaScript events.

b) Instead of using alerts for error messages, I would like to incorporate error messages within a span tag or add another element.

If anyone could guide me in the right direction, it would be greatly appreciated. Thank you in advance!

Below is the code I am currently working with:

LIVE DEMO

@HostListener('keyup',['$event'])
   onkeyup(event:any){

   if (this.control.control.value.match(/<script.*?>.+<\/script>/i)) {
       alert('HTML script tags are not allowed.');
       }
   else if(this.control.control.value.match(/<\/?\w+ +[^>]*on[a-z]+=["'].+["'][^>]*>/gi)){
    alert('HTML event handlers are not allowed.');
   }
 }

Answer №1

To incorporate additional spans, it is recommended to include custom components. When adding DOM elements in Angular, it is best practice to utilize a structural directive such as *directive.

This particular structural directive acts as a wrapper and does not directly reference the applied element. Therefore, you must use the native element to access the next sibling.

Angular suggests that the visibility of components should be determined through a service for dynamic components communication. However, implementing changes in your live example can be achieved by following this link: https://stackblitz.com/edit/primeng-dropdown-automation-84vitx

Remember to declare these components in the .module file and mark the custom error components as entry components to enable dynamic loading.

@Component({template:`<span *ngIf="show">No script tags please</span>`})
export class NoScriptComponent{
  public show = false;
};
@Component({template:`<span *ngIf="show">No html tags please</span>`})
export class NoHtmlComponent{
  public show = false;
};
@Directive({
  selector: '[customTextField]'
})
export class CustomDropDownDirective {
 const htmlError;
 const jsError;
  @Output() updateProperty: EventEmitter<any> = new EventEmitter();
  constructor(private el: ElementRef, private template: TemplateRef<any>, private cfr: ComponentFactoryResolver, private vcr: ViewContainerRef) {
   }

  ngOnInit() {
    this.vcr.createEmbeddedView(this.template)
    const next = this.template.elementRef.nativeElement.nextElementSibling;

      next.onkeyup = this.onkeyup.bind(this);
      const cmpJsFactory = this.cfr.resolveComponentFactory(NoScriptComponent);
      this.jsError = this.vcr.createComponent(cmpJsFactory)
      const cmpHtmlFactory = this.cfr.resolveComponentFactory(NoHtmlComponent);
      this.htmlError = this.vcr.createComponent(cmpHtmlFactory)

  }

    onkeyup(event:any){
    const value = event.target.value;
    if (value.match(/<script.*?>.+<\/script>/i)) {
      this.jsError.instance.show=true;


        }
    else if(value.match(/<\/?\w+ +[^>]*on[a-z]+=["'].+["'][^>]*>/gi)){
      this.htmlError.instance.show=true;
    } else {
            this.jsError.instance.show= false;
            this.htmlError.instance.show= false;

    }
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging constructors for injecting dependencies in Angular is a key practice for enhancing modularity and maintainability

After reviewing the Angular Official documents and various blogs, I noticed that there are two different syntaxes for Dependency Injection (DI) when used within the constructor. Sometimes this is utilized, while other times it is not. This leads to the que ...

The issue with ngModel in Angular is that it fails to update the value within the component

My ngModel doesn't seem to be functioning properly when I use it with a textbox in my application. This is the code snippet from app.component.html: <input type="text" [value]="name" [ngModel]="name"> Name is: {{na ...

Is it possible to eliminate the array from a property using TypeScript?

Presenting my current model: export interface SizeAndColors { size: string; color: string; }[]; In addition to the above, I also have another model where I require the SizeAndColors interface but without an array. export interface Cart { options: ...

Utilizing the power of Angular 4 in combination with mailgun

I need assistance with setting up an email form on my website using Angular 4 and Mailgun as the mail service. I have a method in my mail service file to send messages, but I keep encountering a Bad Request error stating that 'from' is not presen ...

Reorganize mat-table rows using Angular Material's drag-and-drop feature

One of the new features that came with Angular 7 is the powerful DragDropModule: https://material.angular.io/cdk/drag-drop/examples The documentation covers rearranging items in lists and transferring them between different lists, but it doesn't ment ...

Fixing the forwardRef issue with react-router-dom and material-ui

Despite implementing the forwardRef as recommended in various posts and Material-UI website examples, I am still encountering a warning in the console that has me puzzled. I am working on setting up a drawer with a list of items that are React Router link ...

Is there a way to effortlessly update a translation file in Angular 6 using a user-friendly interface?

In my Angular 6 application, I am utilizing ngx-translate and have en.json and nb.json translation files in the assets folder. I've implemented a UI to modify the values of the translation keys, but I'm unsure how to save these changes back to th ...

What is the best way to integrate AWS-Amplify Auth into componentized functions?

Issue: I am encountering an error when attempting to utilize Auth from AWS-Amplify in separate functions within a componentized structure, specifically in a helper.ts file. Usage: employerID: Auth.user.attributes["custom:id"], Error Message: Pr ...

Guide to Triggering a Page View Event in Google Tag Manager with Angular

Previously, I manually fired the Page View Event using JavaScript from app.component.ts while directly accessing Google Analytics: declare var gtag: Function; ... constructor(private router: Router) { const navEndEvents = this.router.events.pipe( fil ...

Having Trouble with Angular 6 Subject Subscription

I have created an HTTP interceptor in Angular that emits a 'string' when a request starts and ends: @Injectable({ providedIn: 'root' }) export class LoadingIndicatorService implements HttpInterceptor { private loadingIndicatorSour ...

Unable to assign value to a public variable in Angular

I am facing an issue where I am trying to retrieve a value from the localStorage and assign it to a variable. However, when I try to use that variable in functions, it is coming up as undefined. code export class DashboardService { public token: any; ...

Utilizing Typescript to retrieve a specific object property using square brackets and a variable

How can we correctly access a JavaScript object in TypeScript using variable evaluation with bracket notation, such as myObject[myVariable], when the value of the variable is unknown initially? In the code below, an error occurs due to the uncertainty of ...

Navigating to a specific router outlet in Angular programmatically - Tips for changing routes in a TypeScript file

I am encountering an issue with my side navigation and the named router outlet within it. Specifically, I am attempting to assign the "aside" named router outlet to a sub component called "top-words-aside", but it seems unable to locate the URL segment. r ...

Why is it that when the form is submitted, the value becomes unclear?

This is a form with HTML and TypeScript code that I am working on. <form> <div class="form-group"> <input class="form-control" ([ngModel])="login" placeholder="Login" required> </div> <div class="form-group"> &l ...

Ensuring thoroughness in validation without the use of specific text strings

Implementing the assignment or assertion of never at the end of a function is a strategy commonly used in Typescript to ensure exhaustive checks at compile time. To enable the compiler to recognize this, explicit strings are needed for it to check against ...

Issues with Angular 5 and Firebase integration

After updating my computer to High Sierra with a clean install, reinstalling the angular-cli, and cloning one of my previous projects that uses Firebase and angularfirebase2, I encountered an issue where any operation to get data from Firebase is not worki ...

Dynamically manipulate menu items in material-ui and react by adding, removing, editing, or toggling their state

I have scoured every corner of the internet in search of an answer to this dilemma. Imagine a scenario where there is a menu located at the top right of a navigation bar, initially showcasing TWO options (1. Login. 2. Register). When a user clicks on eithe ...

Unable to loop through the Array

let Users = [ { name: 'John', id: '1', jp: 'USA' }, { name: 'Jane', id: '2', jp: 'Japan' }, ]; export function DisplayUsers(usersList) { return ( <div> {usersList?.map((user ...

Uploading images using multipart in react is causing an error and cannot be completed

Trying to upload images in the database using multipart is causing an error from the API saying 'Files can't be uploaded". Checking the API in postman shows it is working fine there. There seems to be an issue with my code, but I can't ...

Why is TypeScript unable to recognize package exports? (using CommonJS as the module system and Node as the module resolution)

I have an NPM package that is built for ESM and CJS formats. The package has a dist folder in the root directory, which contains: dist/esm - modules with ESM dist/cjs - modules with CJS dist/types - typings for all modules In the package.json file, there ...