Validating Angular UI without requiring an input field (validating an expression)

Currently, I am utilizing ui-validate utilities available at https://github.com/angular-ui/ui-validate

The issue I am facing involves validating an expression on a form without an input field. To illustrate, consider the following object:

$scope.item = { field1 : 0, field2: 0, field3: 0 };

I aim to receive an error based on the provided expression: field1 + field2 + field3 == 0

This validation pertains to the entire form, not just specific inputs.

Answer №1

To implement validation function, consider the following example using ui-validate:

$scope.checkValidation = function () {
    var total = 0;

    // Calculate sum excluding Angular keys
    angular.forEach($scope.dataItems, function (val, k) {
        // Add a condition "angular.isNumber(val)" for text fields if required
        if (k.charAt(0) !== '$') {
            // Convert to integer using "parseInt()" method if values are strings
            total += val;
        }
    });

    return total !== 0;
}

Add the validation display in your form:

<form>
    <div ng-show="!checkValidation()">Error Detected. Total cannot be zero</div>
    <!-- Include your input fields here -->
</form>

Answer №2

The use of ui-validate is restricted to input tags within the requirement of ng-model. Alternatively, binding ng-show to a function would serve the same purpose. For instance, refer to this demonstration: http://example.com/code123

angular.module('validationApp', ['ngMessages'])
  .controller('formController', FormCtrl);

function FormCtrl() {
  vm = this;  
  vm.data = { value1 : 0, value2: 0, value3: 0 };
  vm.checkValidity = validateFunction;
    
    function validateFunction() {
      // Check if the form data is valid.
      return (vm.data.value1 + vm.data.value2 + vm.data.value3 == 0);
    };
}
<div ng-app='validationApp' ng-controller="formController as vm">
  <form name="sampleForm">
    <label for="value1">Value 1</label>
   <input type="number" name="value1" ng-model="vm.data.value1"/>
    <label for="value2">Value 2</label>
    <input type="number" name="value2" ng-model="vm.data.value2"/>
    <label for="value3">Value 3</label>
    <input type="number" name="value3" ng-model="vm.data.value3"/>
    <div ng-show="vm.checkValidity()">
  <div class="error">Invalid form entry.</div>
</div>
    <button>Submit</button>
    </form>
</div>

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 could be causing JavaScript fetch to only send OPTIONS requests instead of the expected calls?

I'm having an issue with my AJAX request using javascript fetch. It's only sending an OPTIONS call and not proceeding to make further calls. What's strange is that the response header seems fine, and $.ajax is working as expected. Check out ...

Unable to retrieve the image

When trying to fetch an image, I encountered the following error: Failed to load resource: the server responded with a status of 404 (Not Found) TopBar.jsx import { useContext } from "react"; import { Link } from "react-router-dom"; ...

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...

Tips for choosing a single checkbox from a set of multiple checkboxes in React.js

I iterated through a list of objects to generate table rows, each containing an input tag with the type set as checkbox. const [ isChecked, setIsChecked ] = useState(false); const handleChange = (e) => { setIsChecked(e.target.checked) ...

What is the best way to rotate a cube when it is clicked on?

My current project involves rotating a cube by clicking on buttons either on the cube itself or floating next to it. At the moment, I have them floating for easier testing purposes, but placing them directly on the cube is not an issue. The main issue I&a ...

Retrieving Information from JSON File Using a Variable (JavaScript/Discord.js)

While I was coding my Discord bot, I encountered an unexpected issue. Normally, after linking a JSON file, you can access data by using jsonFile.path to retrieve specific information. However, I faced a challenge where I needed to replace the path with a ...

The lifecycle of XMLHTTPRequest objects in JavaScript - from creation to destruction

After years of working with traditional compiled object-oriented languages like C++ and .NET programming, I decided to dip my toes into JavaScript for a new project. As I was experimenting with AJAX, I stumbled upon a perplexing aspect related to how objec ...

JSON syntax error: "r" is not a valid token at the beginning position

Currently, I am in the process of developing a web server that is based on STM32 MCU. The workflow involves the browser sending a request to the MCU, which responds with a web HTML file. Users can then adjust parameters and use a form to submit them back t ...

Every time Chrome on Android returns a keyCode of 229

Here is a snippet of code that I am having trouble with: ... @HostListener('keydown', ['$event']) onKeyDown(evt: KeyboardEvent) { console.log('KeyCode : ' + evt.keyCode); console.log('Which : ' + evt.which); ...

Grabbing data using @RequestParam and $http.post in angularjs I will

I need help sending an array arr=["xxx.yyy","zzz.vvv"] over to a spring endpoint in this manner: $http.post("url",arr) On the spring side, I have the following setup: @PostMapping(value = "url") public Set<String> func(@RequestParam(name="ar ...

When the ng-click event is triggered, all other div elements within the ng-repeat that do not have the same $index value

My goal is quite similar to an accordion. In a simple explanation, I have an ng-repeat with an <a> tag that, when clicked, shows another div called "Printpanel" nested inside it using ng-show. Whenever the user clicks on another <a> tag, I wa ...

Files with extensions containing wildcards will trigger a 404 error when accessed from the public folder in NextJS

I have successfully set up my public folder to serve static files, however I am encountering an issue with files that have a leading dot in their filename (.**). Specifically, I need to host the "well-known" text file for apple-pay domain verification, wh ...

Webstorm 2016.1 encountering difficulties accessing JavaScript files

Recently, I upgraded my Webstorm to version 2016.1.1 and everything seemed to be working well. However, I encountered an issue where I can't open any of my *.js files in the editor. Despite restarting Webstorm and my computer multiple times, as well a ...

Maintaining hover effects even when elements are not in view

I am facing an issue with my absolutely positioned <div> (which serves as a menu) located in the corner of a webpage. The problem arises when I try to animate it on hover, but as soon as the cursor moves beyond the viewport, the hover action stops. I ...

Utilizing a variable name as an object key in TypeScript

Can this be achieved? static readonly statusMapping: { [key in UploadStatus]: PopupMessageStatus } = { UploadStatus.COMPLETED : PopupMessageStatus.COMPLETED } UploadStatus is an enum with numeric values, where UploadStatus.COMPLETED = 0 p ...

Tips for effectively downsizing an HTML Canvas to achieve high-quality images

Introduction I am currently facing issues with blurry visuals in my canvas animation, especially on devices with high pixel densities like mobile and retina screens. In order to address this problem, I have researched canvas down-scaling techniques and f ...

Tips for organizing an AngularJS bootstrap Modal for a search feature

I need help with integrating AngularJs, bootstrap, and an API to populate a bootstrap modal popover with JSON data upon clicking a search function button. While I have successfully implemented the data flow, I am struggling to trigger the modal using the b ...

How to utilize a parameter value as the name of an array in Jquery

I am encountering an issue with the following lines of code: $(document).ready(function () { getJsonDataToSelect("ajax/json/assi.hotel.json", '#assi_hotel', 'hotelName'); }); function getJsonDataToSelect(url, id, key){ ...

By utilizing the HTML element ID to retrieve the input value, it is possible that the object in Typescript may be null

When coding a login feature with next.js, I encountered an issue: import type { NextPage } from 'next' import Head from 'next/head' import styles from '../styles/Home.module.css' import Router from 'nex ...

Enhance videojs player source with personalized headers

Currently, I have a backend API running on Express that manages a streaming video m3u8 file. The endpoint for this file is: http://localhost:3000/api/stream.m3u8 It is important to note that access to this endpoint requires a valid user token. router r ...