innovative specialized validator for dynamic input in template-driven form

STACKBLITZ

  • Ensure killerString has a number in the first position
  • The combined length of string1 + string2 + killerstring should be less than 15 characters
  • I attempted to customize the pattern validator from Angular sources.

How can I create a customValidator with dynamic data attached? There doesn't seem to be a way to attach my dynamic information to an input field directly.

Any suggestions?


With assistance from Syed, I made progress... although it's quite hacky and may not function correctly with multiple fields using my customLength validator:

https://stackblitz.com/edit/angular-4cvomu-zjlht5


Update 2

I discovered a SOLUTION THAT WORKS with the help of this video and that Stack Overflow post.

One issue still remains:

  • Updating string1 or string2 does not trigger validation in killerInput...

Answer №1

After reviewing your latest post, it appears that you will need to monitor changes in @Input within the directive. This can be achieved using ngChanges and registerOnValidatorChange, allowing you to set up a callback function to execute whenever the validator inputs are modified.

To apply the killerInput class with a template variable, ngClass, and some styling:

HTML:

  <input matInput #myInput=ngModel [ngClass]="{'error-class': myInput.invalid}" ....">

Directive

.....

  private _onChange: () => void;

  registerOnValidatorChange(fn: () => void): void { this._onChange = fn; }

  ngOnChanges(changes: SimpleChanges): void {

    if ('customLength' in changes) {
      if (this._onChange) this._onChange();
    }
  }

CSS

.error-class{
  border: 2px solid  red
}

DEMO

For more information, you may find this article helpful.

Answer №2

Revise the lines below and test for changes

modified-input-error-state.ts

from

const total_name = customLength.arr.join();

if (total_name.length > customLength.maxLength) {

to

const total_name = customLength.arr?customLength.arr.join(''):'';

if (total_name.length < customLength.maxLength) {

updated-input-error-state.html

from

<input matInput placeholder="killerstring" [(ngModel)]="killerstring" name = "TDkillerstring" #TDkillerstring = "ngModel" required [pattern]="pat1" [customLength]="{arr: [string1, string2], maxLength: 15}">

to

<input matInput placeholder="killerstring" [(ngModel)]="killerstring" name = "TDkillerstring" #TDkillerstring = "ngModel" required [pattern]="pat1" [customLength]="{arr: [string1, string2, killerstring], maxLength: 15}">

You will receive an error message if the combined length of characters in all 3 textboxes exceeds 15.

I have made the updates in my code on stackblitz. Please review it here

https://stackblitz.com/edit/angular-4cvomu-7jpviu

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

There is no default export defined in Typescript

Currently, I am in the process of developing an npm module that serves as a basic logger. The initial implementation was done using plain JS: logger.js class Logger { // additional code } module.exports = Logger; The above code works seamlessly in a ...

The cdkDragMoved event now provides the pointerPosition using the clientX and clientY coordinates rather than the container

I'm currently working on retrieving the x and y coordinates of a box based on its position within the container. Here's an example that I found on https://material.angular.io. To see how the cdkDragMoved event works, you can check out my small d ...

Is it possible to utilize enums as keys in a Json structure?

I am currently utilizing TypeScript in conjunction with Node.js (MEAN stack). My aim is to incorporate an enum within the property/schema of a JSON object. An example of the enum would be: enum KeyEnums { A: "featureA", B: "featureB&qu ...

Locating the ASP.NET validator's Control with the help of JQUERY or basic Javascript

On my webpage, I have several textboxes with corresponding ASP.NET validators for validation. I know that I can validate all the validators using a JavaScript function: Page_ClientValidate("myvalidators") where "myvalidators" is the group name of my val ...

Issue with retrieving JSON objects in Next.js

I've been developing a straightforward crypto price tracker using the coingecko API. At the moment, my code is unable to retrieve any of the JSON objects from the API link, and curiously, no errors or warnings are being generated to indicate what the ...

Is there a way to pass promises to different middleware functions and get them resolved there?

In an attempt to streamline my code, I am working on a generic function that can manage promises efficiently. Currently, I have promises set up in main.ts and when a request is received, I would like to pass these promises to the common function for execu ...

What is the process for launching a TypeScript VS Code extension from a locally cloned Git repository?

Recently, I made a helpful change by modifying the JavaScript of a VSCode extension that was installed in .vscode/extensions. Following this, I decided to fork and clone the git repo with the intention of creating a pull request. To my surprise, I discove ...

lines stay unbroken in angular

I am encountering an issue when I execute the following code: DetailDisplayer(row) : String { let resultAsString = ""; console.log(row.metadata.questions.length); (row.metadata.questions.length != 0 )?resultAsString += "Questions ...

Hiding a specific tag with vanilla JavaScript based on its content

I am facing a challenge with my code that is supposed to hide div elements containing a specific word along with additional text. I have tried multiple solutions but none seem to work effectively. Any assistance on how to hide divs properly will be greatl ...

Issue TS2322 states that the type 'Observable<{} | T>' cannot be assigned to type 'Observable<T>'

Recently, I came across a useful example of error handling with the async pipe in Angular on this website: However, when attempting to implement it in Angular 7, I encountered compilation errors. readonly data$: Observable<T>; constructor(data: ...

When using Selenium and C# to scrape an Angular website, the result is the Angular script rather than the fully rendered web page

It appears that Selenium is only able to see the HTML that is initially loaded on a webpage, not any changes or updates made after. This behavior has been consistent across different browsers like IE, Chrome, and PhantomJS. Even the built-in Chrome debugge ...

What could be the reason for encountering a Typescript ts(2345) error while trying to pass a mocked constant to .mockResolvedValue()?

Within my test.tsx file, I have the following code snippet: test('Photos will load', async () => { const mockCuratedPhotos = jest.spyOn(endpoints, 'getCuratedPhotos'); mockCuratedPhotos.mockResolvedValue(mockPhotos); awa ...

Navigating to a child component in AngularLooking for a way to direct

I'm currently working on an angular application that follows a parent and sub components structure. I've encountered some difficulties when trying to navigate to the sub structures. While the main routes are functioning properly, the challenge l ...

Setting up the foundations in Angular 4

Using WebStorm 2017.1.4, I am working on creating the front end of my J2EE application. Within this project, I have two components: "about" and "contacts". In the latter component, my goal is to include all contacts from a MySQL database. However, I encoun ...

In Angular, encountering difficulty accessing object members within an array when using custom pipes

Here is a custom pipe that I have created, but I am facing an issue accessing the members of the customfilter array, which is of type Item. import { Pipe, PipeTransform } from '@angular/core'; import {Bus} from '/home/pavan/Desktop/Pavan ...

What could be causing TypeScript to infer an empty object in this straightforward scenario?

Experience this live showcase. Presented with the code below: type Transformer<T> = (t: T) => T; const identity = <T>(a: T) => a; interface HardInferenceFn { <T>(value: T, transform: Transformer<T> | T): T } declare co ...

Submitting a specific form when a change occurs in CodeIgniter

I am currently developing a POS web application. My current task involves creating a form for each item in the cart/order, meaning multiple forms generated in a loop with unique IDs (e.g. 'id'=>'cart_'.$line )(cart_1, cart_2). I hav ...

Experiencing challenges with connecting my AngularJS frontend to a Java Maven backend using Docker

I have built my front-end application in Angular and created back-end REST services using Java with the Maven plugin. My goal is to containerize the web service using Docker, but I am facing challenges in connecting my front-end and back-end (which contain ...

Unable to locate the type definition file for 'jquery'

After updating my NuGet packages, I encountered an issue where I can no longer compile due to an error related to the bootstrap definition file not being able to find the jquery definition file within my project. Prior to the update, the directory structu ...

What is the best way to terminate a file upload initiated by ajaxSubmit() in jQuery?

A snippet of code I currently have is: UploadWidget.prototype.setup_form_handling = function() { var _upload_widget = this; $('form#uploader') .unbind('trigger-submit-form') // Possibly a custom method by our company . ...