How can I programmatically set an input to $valid within an AngularJS controller?

Implementing the TokenInput plugin alongside AngularJS formController validation.

Currently, I am working on verifying if a field contains text and then marking it as valid. However, the complication arises from the plugin creating its own input along with ul+li for styling.

With access to addItem (formname) and controller capabilities, the goal is to set it to $valid.

Markup.

<form class="form-horizontal add-inventory-item" name="addItem">
     <input id="capabilities" name="capabilities" token-input data-ng-model="inventoryCapabilitiesAutoComplete" data-on-add="addCapability()" data-on-delete="removeCapability()" required>
     <div class="required" data-ng-show="addItem.capabilities.$error.required" title="Please enter capability."></div>
</form>

JavaScript.

$scope.capabilityValidation = function (capability) {
  if (capability.name !== "") {
    addItem.capabilities.$valid = true;
    addItem.capabilities.$error.required = false;
  } else {
    addItem.capabilities.$valid = false;
    addItem.capabilities.$error.required = true;
  }
};

The capabilityValidation function is triggered when the TokenInput has an entry and the object is passed in.

UPDATE:

Realized that ng-model on my input performs actions and retrieves autocomplete results, making it challenging to achieve ng-valid functionality since it depends on the model.

$scope.inventoryCapabilitiesAutoComplete = {
  options: {
    tokenLimit: null
  },
  source: urlHelper.getAutoComplete('capability')
};

This autocomplete implementation was not authored by me. Is there an alternative approach where I can manipulate the ng-model attribute and relocate the model function elsewhere?

Answer №1

Modifying a form's validity directly is not possible. The form's validity depends on the validity of all descendant inputs - if they are valid, the form is valid; if not, it is not.

To alter the validity of an input element, you should do as follows:

updateItem.availability.$setValidity("outOfStock", false);

By setting the validity to false for this input, you make both the input and the form invalid. You can also identify which specific error is causing the validation failure.

updateItem.availability.errors.outOfStock == true;

Answer №2

Despite the lack of helpful answers above, I eventually stumbled upon a useful solution after an extensive search.

My problem was resolved by utilizing the following code to manually set the input field to ng-invalid (to set it as ng-valid, change it to 'true'):

$scope.myForm.inputName.$setValidity('required', false);

Answer №3

After encountering a similar issue, I found a solution by including a hidden field to store the invalid state.

<input type="hidden" ng-model="vm.application.isComplete" required="" />

In my scenario, I had a boolean value that needed to be selected using buttons. If 'yes' was chosen, an entity would be added and the button state changed. The form remained invalid until all questions were answered with one button in each pair clicked.

vm.selectSchool = function (attended) { 
  vm.application.hasGraduatedHighSchool = attended;
  applicationService.addSchool(attended, 1, vm.application);
}
<input type="hidden" ng-model="vm.application.hasGraduatedHighSchool" required="" />
<div class="row">
  <div class="col-lg-3"><label>Did You Graduate High School?</label><label class="required" ng-hide="vm.application.hasGraduatedHighSchool != undefined">*</label></div>
  <div class="col-lg-2">
    <button value="Yes" title="Yes" ng-click="vm.selectSchool(true)" class="btn btn-default" ng-class="{'btn-success': vm.application.hasGraduatedHighSchool == true}">Yes</button>
    <button value="No" title="No" ng-click="vm.selectSchool(false)" class="btn btn-default" ng-class="{'btn-success':  vm.application.hasGraduatedHighSchool == false}">No</button>
  </div>
</div>

Answer №4

It's quite straightforward. For instance: in your JS controller, you can do the following:

$scope.inputngmodel.$valid = false;

or

$scope.inputngmodel.$invalid = true;

or

$scope.formname.inputngmodel.$valid = false;

or

$scope.formname.inputngmodel.$invalid = true;

All of these methods have worked for me in various scenarios. Let me know if this helps solve your issue.

Answer №5

In order to resolve the date error, I found that deleting the error before using $setValidity was necessary to properly mark the form as valid.

delete currentmodal.form.$error.date;
currentmodal.form.$setValidity('myDate', true);

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

Attempting to transform the items within my JSON array into my KO observable function

I am currently working with a JSON array that I have read in. My goal is to convert each object within the array into a Knockout (KO) observable so that it can be properly mapped to the function. function Person(data) { this.name = ko.observable(data. ...

What is the process for transforming an array into an array object using javascript?

Here is a situation where I need to upload a text file that contains data in the following format: a1,b1,,c1,d1, a2,b2,,c2,d2, After reading and splitting the data with ("\n"), it results in an array like this: array=[array[0]:[a1,b1,,c1,d1] ...

Tips for enhancing the appearance of a dir-paginate

As a newcomer to AngularJS, I'm interested in learning how to apply styling to a pagination box. Below is the code for displaying a rectangular box view: ` <dir-pagination-controls max- size = "10" direction-links = "true" ...

Mistake in Resource URL for BreezeJS using C# WebAPI with OData

My project setup involves using BreezeJS/Angular/WebAPI(OData) to make GET calls like this: breeze.EntityQuery .from(resource) .using(manager) .execute() .then(function (data) { deferred.resolve(da ...

Trilateration of three-dimensional points using K vertices on each face

I'm currently working on a project using Three.js and I have a set of 3D points in the form of (x, y, z) coordinates, as well as a series of faces. Each face consists of K points and can be either convex or concave in shape. Despite consulting the doc ...

javascript issue with showing content on click

I'm currently working on a school assignment where I am using the onclick() function to display information about an object. However, I am facing an issue where the information is not popping up as expected. HTML <!DOCTYPE html> <html> ...

Change the field of view (FOV) of the Three.js camera according to

Is there a way to modify the standard Three.js resize code so that the scene scales with the DOM element's width as it does with the height? Currently, the scene scales in relation to the element's height, but when the width decreases, the model ...

Looking for assistance with PHP and JavaScript integration

I am struggling with an update-like function that I need help with: <html> $result = mysql_query("SELECT *FROM tbl_a LEFT JOIN tbl_b lass ON tbl_b.b_id=a.class_id LEFT JOIN category ON category.category_id=tbl_a.category_id WHERE list ='{$id}&a ...

How can I arrange the ng-class based on the clicked item's order?

http://plnkr.co/edit/pUtuZy?p=preview In this scenario, there are three different border classes available: .border1 { border: 1px solid #66FFFF; } .border2 { border: 1px solid #33CCFF; } .border3 { border: 1px solid #0099FF; } The goal is to as ...

What are the potential causes of receiving the error message "No Data Received ERR_EMPTY_RESPONSE"?

I often encounter this issue on my website, especially when I have a thread open. It seems to happen whenever I am actively checking for new posts and notifications via Ajax every 10 seconds or so. However, I'm not sure if this continuous reloading is ...

After successfully sending a GET request to the API, the Next.js 13.4.3 website still does not reflect new posts added on the hosting platform

I am currently using Next.js version 13.4.3 in my app directory to create a blog site. However, I am facing an issue. When I run npm run build locally on my computer and then start with npm run start, the new posts are displayed normally after adding them ...

Tips for managing data transfer between an Angular application and an HTML WYSIWYG editor

Considering using a node/express backend with MongoDB seems to be the way forward for this situation... My ultimate goal is to save the content from the editable div to the backend so it can be retrieved and displayed later - either in a non-editable HTML ...

"Creating a function in JavaScript that deals with an array containing multiple

While working on a task involving this function, I noticed that it is not returning the values as expected. function intersection(arrays) { return arrays; } console.log(intersection([5, 10, 15, 20],[15, 88, 1, 5, 7],[1, 10, 15, 5, 20])); OUTPUT [5, 10, ...

The capacity to rotate div containers, adjust their dimensions, and engage with the content within

I'm attempting to design small clickable div boxes that flip 180° when clicked to reveal interactive content. This includes the ability to click links, copy text, or manipulate the content with additional buttons. Although I've successfully ach ...

Creating a delayed queue using RxJS Observables can provide a powerful and

Imagine we have a line of true or false statements (we're not using a complicated data structure because we only want to store the order). Statements can be added to the line at any time and pace. An observer will remove items from this line and make ...

AngularJS ng-switch-trigger enclosed within its own ng-switch-wrapper

In my current project, I am working on switching between two buttons that act as their own triggers for the switch. To illustrate further: <span ng-switch on="patientSwitch"> <span ng-switch-when="edit"> <button ng-click="patien ...

How to successfully send data props from child components to parent in Vue3

I am currently working on a personal project to add to my portfolio. The project involves creating a registration site where users can input their personal data, shipping information, and then review everything before submission. To streamline the process ...

Having trouble retrieving records using findOne() when using a custom ID for inserting records in mongoDB

After inserting records into my mongoDB schema with the command: > db.records.insert( { _id: "6", "name": "Ashish", "City": "Dallas" } ) When I attempt to retrieve them using http://localhost:6001/api/employees/, the response I receive is as follows: ...

Tips for implementing a smooth fade-in effect while rotating URLs within an iFrame

As I cycle through a list of URLs, I am displaying each one in an iFrame for a specific amount of time based on the corresponding value in the durations array. (function step(){ $j('.marquee').attr('src',urls[i].innerHTML); setTime ...

Leveraging NestJs Libraries within Your Nx Monorepo Main Application

I am currently part of a collaborative Nx monorepo workspace. The setup of the workspace looks something like this: https://i.stack.imgur.com/zenPw.png Within the structure, the api functions as a NestJS application while the data-access-scripts-execute ...