Applying the has-error class dynamically in AngularJS to enhance input field styling

I have a scenario where HTML is being dynamically generated from JSON, and I am looking to incorporate validation logic into the process.

For better understanding, here is an example snippet:

<div  ng-switch on="field.type" ng-hide="{{ field.hide }}">
<div ng-switch-when="input" class= "col-md-6" ng-class="{'has-error': reqField(field.name, entity[field.name]) }">
    <input
        ng-model="entity[field.name]" id="{{field.name}}" class="form-control" 
        type="text" ng-style="setStyle(field.style)" ng-change="{{field.change}}" />
</div>
</div>

    {
    "title": "Json Title",
    "id": "j_id",
    "groupfields": [
        {
            "name": "jsonname",
            "title": "JSON Title",
            "type": "jsonselect",
            "namevalue": "jsonvalue",
            "combo": "jsondropdown",
            "change" : "jsonChanged()"
        },
        {
            "name": "jsonEmail",
            "title": "JSON Email Address",
            "type": "display"
        },
        {
            "name": "jsonPhone",
            "title": "JSON Phone Number",
            "type": "display"
        }
    ]
},  {
    "title": "Json Title",
    "id": "j_id",
    "groupfields": [
        {
            "name": "jsonname",
            "title": "JSON Title",
            "type": "jsonselect",
            "namevalue": "jsonvalue",
            "combo": "jsondropdown",
            "change" : "jsonChanged()"
        },
        {
            "name": "jsonEmail",
            "title": "JSON Email Address",
            "type": "display"
        },
        {
            "name": "jsonPhone",
            "title": "JSON Phone Number",
            "type": "display"
        }
    ]
},

if (entityName) {
    return false;
} else {
    return true;
}

To provide clarity, for instance: 'field.type' within the ng-switch refers to the "type" in the JSON - enabling us to display specific HTML div based on various JSON keys/values relationships.

This suggests that a single HTML div could potentially generate multiple input fields, requiring dynamic handling.

My goal is to introduce validation when a required field is left empty. Currently, I attempted implementing ng-class="{has-error': } which calls my function reqField. However, due to this function being executed for EVERY field with "type": jsonselect, it inefficiently checks if the field is empty, causing speed and usability issues (significant lag).

The JavaScript mentioned above essentially reflects the logic of the function reqField() as it verifies the emptiness of the field (inefficient given the volume).

My aim is to instead utilize something like ng-required={{field.required}}, incorporating a new key/value in the JSON dictating whether the field should be mandatory, such as:

 {
"title": "Json Title",
"id": "j_id",
"groupfields": [
    {
        "name": "jsonname",
        "title": "JSON Title",
        "type": "jsonselect",
        "namevalue": "jsonvalue",
        "combo": "jsondropdown",
        "change" : "jsonChanged()"
    },
    {
        "name": "jsonEmail",
        "title": "JSON Email Address",
        "type": "display",
        "required": true
    },
    {
        "name": "jsonPhone",
        "title": "JSON Phone Number",
        "type": "display",
        "required": true
    }
]
},

~ and somehow transmit this data to the ng-class="{has-error': } so that we can take action, like highlighting or any preferred response, once we ascertain if the field has been filled in or not.

Answer №1

AngularJS incorporates form validation within its framework. By using the ng-required directive, you can trigger an error state in the form element. This allows you to customize the appearance with the ng-class attribute as shown below:

<div ng-switch-when="input" class= "col-md-6" ng-class="{'has-error': myForm[field.name].$error.required }">

To make this functionality work, it is essential that both your form and input elements have name attributes defined:

<form name="myForm">
...
  <input name="{{field.name}}" ng-required="field.required">

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 was an error during the module build process, specifically a SyntaxError with an unexpected token at line 10 and column

In our React app, we have a component called OurController. The OurController is functioning properly. However, when we add the following code snippet from an example, the entire app breaks and no pages render in the browser: const TextCell = ({rowIndex, ...

Whenever I attempt to execute yarn build within next.js, an error always seems to occur

When attempting to compile my next.js project using the yarn build command, an error consistently occurs: Error: Export encountered errors on following paths: /settings at D:\web3\futnft\frontend\node_modules\next\ ...

I have to display a pop-up message box after selecting an option from a dropdown menu that fulfills a set of conditions

I am attempting to display a pop-up message when a selection is made on a dropdown menu that meets specific criteria. The dropdown list is generated from a coldfusion output query. I am relatively new to JavaScript, so I may be missing something in my code ...

Can information be securely transmitted using Ajax?

Currently, I am in the process of developing an application in HTML and JavaScript that heavily relies on ajax connections, with the use of the jQuery.ajax() method to simplify the process. I have been pondering the best practices for making secure calls ...

Is there a hover function in jQuery that works with both mouseenter and mouseout events?

I've been facing a slight issue with a list of items using the <li> element. I have a plugin running that dynamically adds a data-tag ID to the data-* attribute of these items. As a result, all items are dynamically added and another function I ...

What is the web address to access when removing an object from the system?

I have set up a local server to experiment with an API in Django. My model, 'Users', is filled with multiple objects and I am utilizing DefaultRouter. If I wanted to DELETE a specific object from this model, what would the URL look like? For ins ...

Sending extensive data to Activity through putExtra();

When the application sends a large number of objects (around 150 objects in JSON format) using intent.putExtra();, some of them are serialized objects. However, the process of opening a new activity is taking approximately 2 seconds. Are there any strate ...

Tips for implementing Papa Parse to parse CSV files using JavaScript

I've been exploring their API without much luck. My goal is to extract data from CSV files that are sent to the client upon server entry. Here's the code snippet I attempted: // Attempting to parse local CSV file Papa.parse("data/premier leagu ...

webdriver: object not found (successfully executes in IDE)

Seeking assistance! I have an input element (shown below) that I am struggling to locate or insert text into. It functions properly in my IDE but not when running my code in Java. The code snippet is as follows: driver.findElement(By.id("searchjobbynam ...

What is the best way to calculate the total sum of a column in Vue JS?

https://i.sstatic.net/K8Rqj.png To manually add a row, each row is stored in the "items" array items: [ { occuGroup:'', constType:'', bfloorArea: 0, cfloorArea: 0 }, ], Below is the code I wrote to calculate the to ...

How to efficiently transfer dynamically generated table row data to JavaScript for database submission using the POST method

Currently, I am working with Laravel and facing an issue related to dynamic rows in my form. Each row has its own form with unique values. My goal is to pass the form data along with values to JavaScript when the submit button is clicked without refreshin ...

using jtemplates to append content rather than replacing it

Currently, I am utilizing jtemplates as my preferred templating solution (a fantastic jQuery plugin). Replacing my asp.net updatepanels with this tool has tremendously boosted the speed of my website. The only snag I've hit is when loading user commen ...

Encountered a type error while attempting to render and define table columns within a material table component in

Hey there! I'm currently using the Material table to create a table view, and here are the columns that I have defined: const columns: TableColumn[] = [ { title: 'TYPE', field: 'type_of_action', highligh ...

JavaScript code to change an array into a stringified format

I have encountered a challenge with transforming an array. The original array looks like this: array = [ { "name": "name", "value": "Olá" }, { "name": "age" ...

A guide on leveraging Jackson for validating duplicate properties

Working with the Jackson JSON library to convert JSON objects into POJO classes has brought up an issue. Specifically, when encountering JSON Objects with duplicate properties: { "name":"xiaopang", "email":"<a href="/cdn-cgi/l/email-protection" cla ...

This API is no longer compatible with India's payment system, so you won't be able to process payments using Next.js, Strapi, or

I am currently developing a website using "next js" as the frontend and "Strapi" as the backend for a simple ecommerce project. The payment gateway being utilized is "Stripe". I have implemented the checkout code in both the frontend and backend, and every ...

What is the best way to assess JavaScript and achieve a result in a Xamarin iOS application?

In my Xamarin iOS application, I have a series of JavaScript functions stored as strings that need to be evaluated in the background. The goal is to pass another JSON string to these functions for processing without any user interference. I am open to usi ...

Enhancing time slot height on Fullcalendar V5: A step-by-step guide

Curious about adjusting the height of time slots in Fullcalendar V5 - any tips? ...

Having trouble with the anchor tag not functioning properly

I'm looking to create a unique video experience by having an iframe video play automatically and opening a third-party video player in a lightbox style when clicked. Currently, the video autoplays, but I want it so that when the user clicks on the vi ...

Filtering in AngularJS can be done by combining two fields at

I attempted to implement similar code for filtering my tasks, but it seems to be malfunctioning. When I use just one filter, everything works fine regardless of which one I choose. However, when I attempt to filter by the second input, it simply does not w ...