Activate validation for a specific field when another field is altered

My custom validation directive is functioning properly, but it relies on another field's value to determine if the first field is valid. The second field happens to be a select list.

I am curious if there is a way to manually trigger validation when the second field is changed, possibly using the ng-change event. How should I go about handling this situation?

This is the code for my directive:

angular.module('myApp', []).
    directive('validage', function () {
        return {
            require: 'ngModel',
            link: function (scope, elem, attr, ngModel) {

                function validate(value) {
                    var valid = true;
                    if ((GetDateDifference(new Date(value), new Date()) < 16 || GetDateDifference(new Date(value), new Date()) > 129)
                    && scope.dep.DependantType == "Spouse") {
                        valid = false;
                    }
                    ngModel.$setValidity('validage', valid);
                    return value;
                }

                //For DOM -> model validation
                ngModel.$parsers.unshift(function (value) {
                    var valid = true;
                    if ((GetDateDifference(new Date(value), new Date()) < 16 || GetDateDifference(new Date(value), new Date()) > 129)
                    && scope.dep.DependantType == "Spouse") {
                        valid = false;
                    }
                    ngModel.$setValidity('validage', valid);
                    return value;
                });

                //For model -> DOM validation
                ngModel.$formatters.unshift(function (value) {
                    var valid = true;
                    if ((GetDateDifference(new Date(value), new Date()) < 16 || GetDateDifference(new Date(value), new Date()) > 129)
                    && scope.dep.DependantType == "Spouse") {
                        valid = false;
                    }
                    ngModel.$setValidity('validage', valid);
                    return value;
                });
            }
        };
    });

If you're unfamiliar with AngularJS, I suggest checking out these two informative articles: part 1 and part 2. These provide an overview of AngularJS forms.

Answer №1

After researching extensively, I discovered a simple way to trigger validation by using the $validate() method on the specified field.
For instance, if your form is identified as my_form (where the form tag has a name="my_form" attribute in the markup) and you want to validate the field named date (with a name="date" attribute for the input field), you can utilize the ng-change event of the second field and execute $scope.my_form.date.$validate(); whenever the ng-change function is triggered.

Answer №2

Dealing with a similar issue, I encountered two form fields named "interval" (for $scope.monitor.interval) and "timeout" (for $scope.monitor.timeout) where the requirement was that timeout should not exceed half of interval.

To address this, I implemented a custom validator for the timeout field to enforce this condition. However, I also needed to ensure that the timeout validator is triggered whenever the interval value changes. This was accomplished by monitoring the monitor.interval property of the model:

function EditMonitorCtrl($scope, $log, dialog, monitor) {
    $scope.monitor = monitor;

    ...

    // Trigger validation for timeout field on interval change
    $scope.$watch("monitor.interval", function() {
        if ($scope.editMonitorDlg.timeout.$viewValue) {          
            $scope.editMonitorDlg.timeout.$setViewValue($scope.editMonitorDlg.timeout.$viewValue);
        }
    });
}

Not including the "if" statement resulted in the removal of the timeout value during dialog initialization.

Answer №3

Struggling with the implementation of

ng-blur="myForm.myField.$validate()"
in AngularJS 1.5, I realized that it might be due to an empty model for myField.

On a positive note,

ng-blur="myForm.myField.$setTouched()"
proved to be effective.

Answer №4

I found that by implementing the directive in the second field and adjusting it to display the error message directly on the erroneous field, I was able to resolve the issue. There may be alternative methods, but this is the approach I ultimately settled on.

Answer №5

To activate validation on the 2nd field, all you need to do is reset it whenever there is a change in the 1st field.

Here's an example using the change event of the 1st field:

const controls:any = control.parent.controls;

if(controls.secondField.value !== ''){
   controls.secondField.setValue(controls.secondField.value);
}

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

Include specific javascript files only for smartphones

Recently, I encountered an issue with a JavaScript code that swaps background images on scroll down. To address the problem with debounce, I ended up setting different debounce times for various browsers (I am aware this is not the ideal solution, but it&a ...

What is the process for turning off deep imports in Tslint or tsconfig?

Is there a way to prevent deep imports in tsconfig? I am looking to limit imports beyond the library path: import { * } from '@geo/map-lib'; Despite my attempts, imports like @geo/map-lib/src/... are still allowed. { "extends": &q ...

An A-frame that continually animates a glTF model to move to the position of the camera within the A-frame

I'm currently working on a virtual reality scene using A-frame () and I'm trying to figure out how to animate a gltf model so that it always follows the camera. Essentially, I want the model to move along with the player's movements. For exa ...

Is there a way for me to verify if my JSON field has been defined?

Currently, I am working on parsing JSON data and attempting to access one of its fields, which happens to be an array. const myObj: MyObj = JSON.parse(myJson); console.log(myObj.myArray); //SyntaxError: Unexpected end of JSON input console.log(myObj.myArr ...

Transmitting an array within the POST request payload

My goal is to send an array to my Node/MongoDB server using an AJAX POST request, along with other variables in the body. Check out the client side JS code below: function setupForm(){ $("#add").submit(function(event) { event.preventDefault() ...

Effortlessly move and rearrange various rows within an HTML table by utilizing JQuery alongside the <thead> elements

My JsFiddle has two tables and I want to switch rows <tr> between them using Jquery. However, due to the presence of the <thead> tag, it is not functioning properly. I suspect that the issue lies with the items in the selector, but I am unsure ...

Merging Documents in PouchDB

I need to retrieve equipment data from pouchdb/couchbase that has users assigned to them. Each piece of equipment has an _id and a checkedOutBy field with the user._id as its value. The employee object contains the user's name. How can I retrieve the ...

Unable to align text to the left after inserting an image with a caption in Froala editors

Here are the steps to reproduce the issue: Begin by opening the Froala editor at . Delete all content in the editor. Insert an image. Add a caption to the image. Click outside the image and attempt to type. Problem: After adding an image caption, any te ...

Utilizing moment.js to showcase the current time of day

Is there a way to show "Sunday Morning" if it's before noon or "Sunday Afternoon" if it's after noon? This code snippet below is what I am currently using to retrieve the current day: var now = moment().format("dddd"); $("#date").append(now); & ...

Utilize Firebase Hosting to Host Your Vue Application

Having some trouble with hosting code on Firebase. Instead of displaying the value, {{Item.name}} is appearing :( Same code works fine on Codepen. Wondering if Firebase accepts vue.min.js? When deployed, the site is showing {{var}} instead of the table va ...

What could be causing the NaN result?

Currently diving into the realm of Javascript, I have encountered an issue where my calculated data is returning as NaN. The desired output should be ar = [37, 36.63, 35.68, 38.81, 37.67, 37.64, 37.64, 39.74, 40.67, 40.61]; ma = [0.00, 0.63, 3.32, 0.81, ...

Trouble obtaining AJAX result using onClick event

As a newbie to AJAX, I am still trying to grasp the concept. My task involves using an AJAX call to extract specified information from an XML file. Even after carefully parsing all tag elements into my JavaScript code, I encounter a problem when attempting ...

Guide to displaying API data in HTML format

This university assignment involves working on a homework project where I need to utilize a public API in HTML. So far, I have successfully called the public API to display a list of radio channels in the left menu (without adding any click functionality). ...

Mobile Size Setting

Could someone please explain to me why when I test this code on Google Chrome using the mobile emulator for Galaxy S3, it displays the correct size (640x360), but when I try to load it on my actual Galaxy S5 or any other device, the size is different from ...

Cannot access array method(s) using MyObject.prototype.reduce callback

As I delve into prototyping, I encountered an issue with using forEach and reduce on my ArraySet prototype. The arrow function callback works well with forEach, but I hit a roadblock with reduce. It seems the notation that works for a normal Array doesn&ap ...

Screenshots showcasing examples of HTML5 Canvas presentations

I recently discovered html2canvas through a question I had asked previously. I'm now trying to figure out how to use it to achieve the following: Generate a live thumbnail of a website. Clicking on the live thumbnail should load a larger image of th ...

Excessively Running Firebase Function Due to setInterval Usage

My Firebase function is set to run every 20 minutes using setInterval, but it seems to be executing more frequently than expected. Here is an excerpt from my code: try { const response = await axios.get( "https://ll.thespacedevs.com/2.0.0/ ...

Issues with refreshing Datatables functionality

I’ve hit a roadblock while troubleshooting this issue, and it’s gotten quite frustrating. That's why I've turned to Stackoverflow for help once again. As a beginner, I ask for your patience and thank you in advance for any assistance. In my ...

Can you provide tips on how to realign an image in a contenteditable DIV in Internet Explorer?

When I have a div with the attribute contenteditable="true" in IE versions 7, 8, and 9, and then click a button to insert an image using the document.execCommand('insertImage') method, the image is successfully inserted. However, the inserted ima ...

Reset AngularJs service data

My goal is to save information in my services similarly to the solution found in : Processing $http response in service app.factory('myService', function($http) { var promise; var myService = { async: function() { if ( !promise ) ...