Implement Validation on class instances in Aurelia without the need for injection

Having trouble with injections in Aurelia and looking for a way to implement Validation, EventAggregator, and Router without using injection.

Check out this example that illustrates the issue I'm facing:

class Profile interacts with the view, creating an object of AddressList that also interacts with the view.

For instance:

@inject(EventAggregator, Validation, Router)
export class Profile{
      addressList: Array<AddressList> = [];
      eventAgg:any;
      _validation:any;
      _router:any;
      constructor(EventAggregator, Validation, Router )
                  {
                   this.eventAgg = EventAggregator;
                   this._validation = Validation;
                   this._router = Router;
                   this.addressList.push(new AddressList());
                  }
}

export class AddressList{
      street1:string = "street1";
      street2:string = "street2";
constructor(){
}

Now, the challenge is to implement validations on the properties of AddressList without passing validation in the constructor of AddressList.

Avoiding:

this.addressList.push(new AddressList(Validation));

This approach may pose issues when passing arguments in the AddressList constructor.

Similarly, difficulties can arise when composing one view-model within another where the constructor expects user-defined arguments.

Your insights are appreciated,

Ankur


Question Updates/Changes

I made the suggested changes as per advice from Matthew James Davis. Still puzzled by why AddressList is showing as undefined.

Updated Code Snippet

import { Factory } from 'aurelia-framework';
import { ObserverLocator } from 'aurelia-framework';
import { EventAggregator } from 'aurelia-event-aggregator';
import { Validation, ensure } from 'aurelia-validation';

@inject(EventAggregator, Validation, Factory.of(AddressList))
export class Profile{
   addressList: Array<AddressList> = [];
      eventAgg:any;
      _validation:any;
      _router:any;
      constructor(EventAggregator, Validation, AddressList)
                  {
                   this.eventAgg = EventAggregator;
                   this._validation = Validation;
                   this.addressList.push(AddressList(["street1","street2"]));
                  }
 }

@inject(Validation)
export class AddressList{
      street1:string = "street1";
      street2:string = "street2";
      constructor(Validation, args){
         this.street1=args[0];
         this.street2=args[1];
     }
}

Error Message from Console

AddressList
function() {
        for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) {
        rest[_key] = arguments[_key];
        }

    return container.invoke(_this2._…
AddressList ()

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

The error seems to be linked to the line in Container.prototype._createInvocationHandler:

 if (fn.inject === undefined)

Where fn is undefined.

Hoping this information helps shed light on the issue. Still working on unraveling the root cause.

Answer №1

To accomplish this task, Patrick suggested utilizing Aurelia's Factory resolver:

import { Factory } from 'aurelia-framework';

@inject(Factory.of(AddressList))
export class Profile {

    addressList: Array<AddressList> = [];

    constructor(AddressList) {
        this.addressList.push(
            AddressList(['123 Elm St.', 'Apt B.'])
        );
    }
}

@inject(Validation)
export class AddressList {

    street1;
    street2;

    constructor(Validation, addressList: string[]) {
        this._validation = Validation;
        this.street1 = addressList[0];
        this.street2 = addressList[1];
    }
}

Answer №2

It might not be the exact issue, but in my experience with typescript, I have found that you also have to import inject from aurelia-framework.

An alternative option could be to inject it in this manner:

private static inject = [EventAggregator, Validation, Factory.of(AddressList)]

However, if you are not utilizing typescript, it may not be necessary to do so.

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

Difficulty arising from implementing v-if as a filter within a v-for loop in Vue.js

I'm struggling a bit with setting up a conditional statement using v-if along with a loop using v-for in Vue. Here's what I have so far: <div class="row form-group" v-for="(article, key, index) in articles" :key="key" v-if="article.pubdate(fi ...

Attempting to embed a secondary window within the primary window using three.js

I am currently working on incorporating a zoomed view of a sphere into a main window that represents the sphere. At this point, I have succeeded in displaying a subwindow at the bottom right corner that contains three axes of the main scene. These axes ro ...

The SSE functionality is effective in a local environment, but encounters issues when deployed on Vercel's

Operating a proxy server, I send a request to OpenAI which responds with a Readable Stream object. The proxy server then redirects these events back to the client. While my code functions properly on a local deployment, it encounters issues when deployed ...

Unable to retrieve POST parameters using Node.js and Express

I'm currently experimenting with a basic example of a Node.js + Express RESTful API. One action I've set up is to simulate a login request. Below is the code snippet: app.js var express = require('express'); var path = require('p ...

Passport Authentication does not initiate a redirect

While working on a local-signup strategy, I encountered an issue where the authentication process against my empty collection was timing out after submitting the form. Despite calling passport.authenticate(), there were no redirects happening and the timeo ...

Combine and inject global SCSS file into all components using browserify and vueify

When developing an app, I utilize browserify along with vueify. My goal is to inject a global SCSS file containing variables, mixins, colors, etc., into Vue so that it is accessible to all components without the need for explicit import statements in each ...

Converting HTML to PDF with rtl support using the JavaScript library jsPDF

I'm attempting to convert HTML to PDF using jsPDF in an Angular 5 project. Below is the code I have so far: import * as jsPDF from "jspdf"; . . . htmlToPdf(){ var doc=new jsPDF(); var specialElementHandlers = { '#content' : function ...

React Forms: Dynamically Updating the User Interface using WithFormik() and Axios GET Response

I've been using withFormik() to create a form for my Gatsby application. Currently, I am implementing a GET request using axios within the handleSubmit() function of withFormik(). Once I receive the response, I want to update it on the UI immediately ...

Fade in/out overlay effect when clicking on a content block

I've hit a roadblock while trying to implement overlay fading in and out to cover a block created by some JavaScript code. Here is a link to the project. When you click on any of the continents, a series of blocks with country flags will appear. You& ...

Create custom AngularJS directives for validation and store them in a variable

Through the use of AngularJS, I've developed a directive called "integer" that invalidates a form if anything other than integers are entered. Because I'm generating the page dynamically by fetching data from the database, it would be helpful to ...

Angular: issue with form validation - password matching is not functioning as expected

I have successfully implemented the registration form with basic validations The code I used can be found in: registration.html <form #registrationForm="ngForm" (ngSubmit)="onFormSubmit()"> ... <div class="form- ...

Node.js is encountering an undefined parameter in the function definition

I've encountered an issue while working on an application utilizing MongoDB as the database and node.js. I have a function that is supposed to receive a parameter named orderedBy, but when I console.log it, it appears as undefined. Can someone help me ...

Struggling to figure out how to properly shuffle my deck of cards array in JavaScript. Can't seem to grasp how to pass the array correctly

Currently, I am engrossed in my personal project and watching tutorials just for the fun of it. My goal is to create a game for my school project which is inspired by a war card game that I used to play as a child - where the highest number wins. I have ...

The jQuery AJAX call is successful in Firefox, but unfortunately, it is not working in Internet Explorer

I've encountered a perplexing issue with an AJAX call. It's functioning perfectly fine in Firefox, but for some reason, it's not working in IE. Curiously, when I include an alert() specifically for IE, I can see the returned content, but the ...

Unveiling the power of experimental decorators in Storybook 8 with NextJS/SWC

I am facing an issue with experimental class decorators in my code, causing the Storybook build to crash. Module build failed (from ./node_modules/@storybook/nextjs/dist/swc/next-swc-loader-patch.js): Error: × Expression expected Despite reading the co ...

Executing functions with directive controllers

Is there a simple way to call a function on a directive controller by accessing the instance using its id from the parent controller? <my-directive id="id1" /> var dirController = getDirectiveByID("id1"); dirController.someFunc(); If you have any ...

Partial data sent through Ajax to PHP file

Encountering a peculiar issue with Ajax where the entire string data is not being sent to the php script. Here is the string: "<p class="MsoNormal" style="text-align:justify"><b><u><span lang="DE" style="font-size:10.0pt;mso-bidi-fon ...

Display a "busy" indicator using Ajax, specifically for requests that take longer to process

Is there a way to delay the appearance of the busy indicator until a certain amount of time has passed? The code I'm using for the busy indicator is quite simple: jQuery.ajaxSetup( { beforeSend:function () { jQuery( "#busy-indicator" ...

Using the jQuery before() method to manipulate form fields

Is it possible to utilize the jQuery before method to insert a form? An example scenario could be as shown below: <script> $(document).ready(function() { $("button").click(function() { $("button").before('<form><input type="text ...

Utilizing a promise instead of making a jQuery ajax request

A scenario I am facing involves a function that is set to execute jquery.ajax and return it as a promise for future processing. However, in certain cases, the function possesses enough information to proceed synchronously without triggering the ajax call. ...