Transmit control statuses to the framework

I have a set of UI Controls that inherit from an abstract control. Within the abstract control, there is a method called isValid which every control must extend in order to return true or false. As a framework, I need to determine whether to mark the controls in red for non-valid cases. Is there a specific design pattern or approach that I should use in this scenario to assist with this?

Answer №1

If you're working in pure JavaScript without the use of frameworks like React, Angular, or jQuery, consider utilizing the existing Observer Pattern within DOM elements to handle updates triggered by changes.

Here's an abstraction:

// Define the AbstractControl class.
var AbstractControl = function() {

}

// Virtual methods.
AbstractControl.prototype.isValid = function() {
    throw new Error('Not implemented.')
}

AbstractControl.prototype.paintGreen = function() {
    // Handling valid scenario.
    throw new Error('Not implemented.')
}

AbstractControl.prototype.paintRed = function() {
    // Handling invalid scenario.
    throw new Error('Not implemented.')
}

// The update function checks the control's validity and triggers appropriate actions.
AbstractControl.prototype.update = function() {
    if (this.isValid()) {
        this.paintGreen();
    } else {
        this.paintRed();
    }
}

Let's create a concrete control class as an example:

// Class representing an email input field, taking a DOM element.
var EmailField = function(element) {
    AbstractControl.call(this, AbstractControl);
    this.element = element;
    // Listens for change events on the element and updates its status.
    this.element.addEventListener("change", this.update.bind(this));
}

// Inherit from AbstractControl.
EmailField.prototype = Object.create(AbstractControl.prototype);
EmailField.prototype.constructor = EmailField;

// Implement virtual methods.

EmailField.prototype.isValid = function() {
    return this.element.value.indexOf("@") >= 0;
}

EmailField.prototype.paintGreen = function() {
    alert("Email is correct. Proceed.")
}

EmailField.prototype.paintRed = function() {
    alert("Invalid email! Please correct.")
}

Usage example:

new EmailField(document.getElementById("emailfield"));

An alert will pop up on every change based on the content of the field. You could modify the behavior to visually indicate the status instead of using alerts.

JSFiddle demo: https://jsfiddle.net/surj64vy/ (demonstrating real-time updates and visual cues instead of alerts)

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

What is the process for including a selected-by option in a VIS network graph?

I'm trying to outline the neighboring nodes of the node that has been selected (highlightNearest). https://i.sstatic.net/lynhu.png Unfortunately, I haven't had success achieving this using JavaScript. Link to StackBlitz ...

Strategies for Resolving Table Alignment Problems using HTML and JavaScript

I am struggling to figure out how this dashboard will function as it is not a live website, but rather a tool that pulls data from a chemical analysis program and displays it in a browser view. My main issue is aligning two tables at the top of the page ...

The functionality of the $.post function is not providing the accurate data in its return

Using $.post to transmit data to my main page from droppable elements is causing an issue. When I echo out the data, the toolbar is also being echoed out along with the fetched data. if (isset($_POST['data'])){ $data = $_POST['data']; ...

Setting the state based on Promise values within a loop

I am currently facing a challenge in my React project where I am using axios to interact with an external API. The goal is to loop through the array of objects retrieved from the API call and utilize the values returned by a separate function within the ...

How do I link JavaScript with a database in Django?

I am currently working on a project using Django and I'm looking to integrate js into it. While I don't have much experience with js, I am interested in learning how to manipulate the database using js. Specifically, I want to implement a delete ...

When using `parseInt` on the string "802.11 auth", the result did not match my expectations

I am developing a data parser that transforms the output of a command into a JSON object for sending to a live logging and graphing platform. All data extracted by the parser is returned as strings, but I need numerical values to be preserved as numbers. H ...

Starting from TypeScript version 5.6, `Buffer` cannot be categorized as either `ArrayBufferView` or `Uint8Array | DataView`

Struggling to make the transition to TypeScript 5.6 Beta, I am encountering these error messages within the node_modules directory. Without making any other modifications, how can I resolve these errors? node_modules/@types/node/buffer.d.ts:632:19 - error ...

TypeScript's type inference feature functions well in scenario one but encounters an error in a different situation

I recently tried out TypeScript's type inference feature, where we don't specify variable types like number, string, or boolean and let TypeScript figure it out during initialization or assignment. However, I encountered some confusion in its be ...

Consistent column heights within each row

I currently have Bootstrap implemented on my website and have integrated jQuery to adjust the height of each column to match the tallest one. However, the issue I am facing is that the height adjustment applies globally across the entire page, rather than ...

Address Book on Rails

Hello, I'm relatively new to this and would be grateful for any assistance. My goal is to utilize the data saved by a user in their address book, and then offer them the option to use that address for delivery. Below is my Address controller: class A ...

What is the best way to alter the class of a <div> element with a specific ID?

In the web app, I have a tabbed page that allows users to filter restaurants based on budget and cuisine. The search results are categorized into meals, snacks, and drinks tabs. Each tab is designed as a button with a corresponding window displayed below ...

Upgrade Angular from 12 to the latest version 13

I recently attempted to upgrade my Angular project from version 12 to 13 Following the recommendations provided in this link, which outlines the official Angular update process, I made sure to make all the necessary changes. List of dependencies for my p ...

The Angular application is experiencing issues following an update from version 11 to version 12

I recently updated my Angular project following these steps: npm cache clean --force npm uninstall @angular/cli@latest @angular/core@latest npm install -g @angular/cli@latest @angular/core@latest After completing the above steps, I proceeded to delete th ...

Execute HTML code within a text field

Is it possible to run html code with javascript inside a text box, similar to w3schools.com? I am working solely with html and javascript. Thank you. For example, I have two text areas - one for inserting html, clicking a button to run the code, and displ ...

Transferring information between two tables in a MongoDb database

My current database in mongo is named "sell" and it contains two tables: "Car" and "Order". In the "Car" table, there is an attribute called "price". When I run the following command in the mongo shell: db.Order.aggregate([ { $lookup: { from: ...

Jest came across a surprising token that it wasn't expecting while working with React and TypeScript in conjunction with Jest and React-testing-L

An unexpected token was encountered by Jest while using React and TypeScript along with Jest and React-testing-Library. Error occurred at: E:\Git\node_modules@mui\x-date-pickers\internals\demo\index.js:1 ({"Object." ...

The content within Contentful is presented in a JSON object format, but accessing specific values is proving to be

I have successfully added two records in the contentful database and now I am attempting to fetch the content from Contentful into my React-hooks website. However, I am facing difficulties retrieving the values for title, description, image, and shortDescr ...

How to identify a button click on an HTML page within an Android WebView

When using my Android app, I encounter an issue with a webview that contains a form and a submit button. The button code snippet is as follows: <button role="button" class="btn ng-binding" ng-click="actions.collect()" tooltip="default" title="Check f ...

using a dynamic v-model as an argument in a function call

I am completely new to using vuejs and currently working on creating a dynamic table. In this table, the left column will contain hidden input fields that will be used to query a database and display the results in a pop-up window for quick referencing. ...

What is the method for bringing in Mongoose to utilize json.parse()?

I'm really eager to utilize this code for importing a JSON file into JavaScript var treeData; var oReq = new XMLHttpRequest(); oReq.onload = reqListener; oReq.open("get", "test.json", true); oReq.send(); function reqListener(e) { treeData = JSON. ...