The error message states: "There is no 'on' property defined for the type 'FluentRules<any, any> | FluentEnsure<any> | FluentRuleCustomizer<any, any>'."

Currently, I am developing aurelia-validation and encountering an issue with the on method from a different overload (FluentRuleCustomizer) class. The code works fine when using ruleBuilder['on'](field);, however, changing it to ruleBuilder.on(field); results in a red squiggly line under ruleBuilder.on(field);. Please refer to the code snippet and screenshot below.

import { ValidationRules, FluentRuleCustomizer, FluentEnsure, FluentRules } from 'aurelia-validation';
import { on } from 'cluster';
export class FormHelper {
  private static initializedForms = [];

  public static initializeFormRules(form) {
    if (this.initializedForms.indexOf(form) > -1) {
      return;
    }
    this.initializedForms.push(form);
    for (const field of form.fields) {
      if (field.validation.isValidate) {
        let ruleBuilder: | FluentRules<any, any> | FluentEnsure<any> | FluentRuleCustomizer<any, any>;
        ruleBuilder = ValidationRules
          .ensure("value")
          .displayName(field.label);

        const rules = Object.keys(field.validation.validationRule)
          .map(key => ({ key, value: field.validation.validationRule[key] }));

        for (const rule of rules) {
          ruleBuilder = ruleBuilder[rule.key](rule.value);
        }
//         ruleBuilder['on'](field);
        ruleBuilder.on(field);
      }
    }
  }
} 

Here is the link to all the exported classes available for aurelia-validation.

Your assistance will be greatly appreciated :)

https://i.sstatic.net/sKjeF.png

Answer №1

The formatting and structure of the aurelia-validation library's typings/API may not be optimal for dynamically constructing rules in this way, so a workaround is required.

To make it work, simply modify your initial declaration like so:

let ruleBuilder: FluentRuleCustomizer<any, any> = ValidationRules
      .ensure("value")
      .displayName(field.label) as any;

Even though it won't initially be a FluentRuleCustomizer (hence why as any is used), it will transform into one after additional rules are applied in the logic that follows. Personally, I believe the .displayName() method should just return a FluentEnsure or FluentRuleCustomizer (both of which have the .on() method that performs similar actions), but that discussion can be saved for another time.

It's advisable to verify that rules have been successfully applied before using the .on() method to avoid errors:

if (rules.length) {
    ruleBuilder.on(field);
}

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

Retrieve all objects of the selected value using Angular autocomplete when an option is selected

I am currently working with an autocomplete component. I am passing an array of objects and would like to retrieve all item information (option) when an option is selected, not just the field value (option.name). <form class="example-form"> ...

Issue arising in Angular 7 due to the binding between the TypeScript (ts) file and HTML file for the property [min]

I am currently utilizing Angular Cli version 7.3.9 In my project, I have implemented a date type input that is intended to display, in its datepicker, starting from the next day after the current date. This is how I approached it in my .ts file: debugger ...

What is the correct way to set up a custom class instance with specific parameters at the top level?

Is it possible to utilize the defineString(), defineInt, ... functions within a top-level custom class constructor? defineString() returns a StringParam object which has a value() method. I am looking to use parameterized configuration to initialize an in ...

How can I arrange selected options at the top in MUI autocomplete?

I am currently working with mui's useAutocomplete hook https://mui.com/material-ui/react-autocomplete/#useautocomplete Is there a way to programmatically sort options and place the selected option at the top using JavaScript sorting, without resorti ...

styled components are having issues with background gradients and opacity not functioning properly

Hello, I am currently working with styled components and have the following global style code: const GlobalStyle = createGlobalStyle` html{ font-family: roboto; background: linear-gradient(45deg,rgba(137,255,255,0.5),rgba(161,252,143, 0 ...

You have to include the necessary request body in the front-end request to address the

After successfully testing a POST request to add a new entity to the database from my project back-end using Postman, I encountered an error when trying to do the same from the front UI (I'm using Angular 4): Required request body is missing. Failed ...

Getting the item that was clicked on a Chart in a PrimeNG chart within an Angular application can be achieved by following these

I am trying to implement a bubble chart and I would like the function to be called when a user clicks on one of the bubbles. What is the best way for me to pass the data to this function? https://i.stack.imgur.com/FYiSP.png <p-chart type="bubble" [da ...

Having trouble with Typescript subtraction yielding unexpected results?

If I have a total amount including VAT and want to separate the net price and the VAT value, how can this be done? For example, if the final price is $80.60 with a VAT rate of 24%, what would be the net price and the VAT value? The correct answer should ...

Issue with ngFor displaying only the second item in the array

There are supposed to be two editable input fields for each section, with corresponding data. However, only the second JSON from the sample is being displayed in both sections. The JSON in the TypeScript file appears as follows: this.sample = [ { "se ...

Issue TS8011 in Angular 6 is related to the restriction on using type arguments only in files with the .ts extension

I have a project in Angular 6 where I need to integrate a JS library. This library is confidential, so I can't disclose its details. The problem I'm facing is that the TypeScript compiler seems to misinterpret characters like <<24>>, ...

Modify a single parameter of an element in a Map

Imagine I have a map data type exampleMap: Map<string, any> The key in the map is always a string, and the corresponding value is an object. This object might look like this: { name: 'sampleName', age: 30} Now, let's say the user se ...

The readAsDataURL method generates an invalid Base64 string for PNG images, while it works properly for JPG/JPEG files

Dealing with a React Native app and attempting to address this particular problem. The base64 is sent to an API and saved in the database as a blob. I understand that it's not ideal practice, but given that this is just a simple student project and no ...

Determine data type based on key of object within a Zod array

Trying to extract the type from a key within an array of objects using Zod presents some challenges, especially when the array is nested within another object. To illustrate the issue: const obj = z.object({ nestedArray: z.array(z.object({ valueIWant: z ...

Can one validate a single route parameter on its own?

Imagine a scenario where the route is structured as follows: companies/{companyId}/departments/{departmentId}/employees How can we validate each of the resource ids (companyId, departmentId) separately? I attempted the following approach, but unfortunate ...

Ways to define the name and components within the <script setup> scope

Is it possible to define the name and components in a <script setup> mode? In a <script> mode, you can do something like this: export default { name: 'App', props: ['foo', 'greetingMessage'], components: { ...

Unable to remove a OneToMany entry in TypeORM

I am currently working with the following database schemas: @Entity() export class Question extends BaseEntity { @PrimaryColumn() messageId: string; @Column() authorId: string; @Column() question: string; @Column("varchar", { arr ...

What is the process for incorporating a restriction in a map within a generic framework?

Note: The explanation provided was not clear enough; you might find it helpful to move on to the next example. I'm facing an issue with the constraints on generics and struggling to identify my mistake. Here is the code snippet: Code snippet goe ...

Can you explain the concept of a mapped type and its practical applications?

What is the function of this? And when would be the best scenario to utilize it? ...

Why am I getting the "Cannot locate control by name" error in my Angular 9 application?

Currently, I am developing a "Tasks" application using Angular 9 and PHP. I encountered a Error: Cannot find control with name: <control name> issue while attempting to pre-fill the update form with existing data. Here is how the form is structured: ...

What is the best way to mock imports in NestJS testing?

I am interested in writing a unit test for my nestjs 'Course' repository service, which has dependencies on Mongoose Model and Redis. courses.repository.ts: import { Injectable, HttpException, NotFoundException } from "@nestjs/common"; ...