The conditional validation feature of the jQuery Validation Engine allows for dynamic validation based on

In my Angular SPA, I have a form that incorporates Jquery validation engine for validation purposes. The form consists of a check box and a text-box. I want the text-box to be required only if the check box is checked, and this functionality is working as intended. However, the issue arises when my ng-submit function is called even in case of a validation error. I am looking to limit this call by using Angular's directive to manage control validations.

<form role="form" name="frmVariableConfig1" class="formValidVariableConfig1 form-inline" novalidate ng-submit="frmVariableConfig1.$valid && vm.saveChanges()">

<span class="checkableBox"><input type="checkbox" item="variable" toggle-selection="toggleSelection('1')" bootstrap-check ng-model="vm.SetThreshold"></span>

<input type="text" ng-model="vm.Threshold" name="cntrlThresh" class="form-control input-sm {{ vm.getValidation(vm.SetThreshold) }}" placeholder="Threshold" check-validation2>

<button type="submit" class="btn btn-sm">Save</button>
</form>   

The `vm.getValidation` function returns "validate[required]" or "" based on the value of `vm.SetThreshold`, which is the model of the checkbox above.

The directive is implemented as follows:

.module('app').directive('checkValidation2', [
function () {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, ngModel) {
            element.closest('form').validationEngine();

            scope.$watch(attrs.ngModel, function (newValue, oldValue) {
                var valid = !element.validationEngine('validate');
                ngModel.$setValidity(element.context.name, valid);
                return valid;
            });
        }
    };
}
]);

UPDATE

Upon page load, the form is initially ng-valid due to no validation being present in the text box. When the checkbox is clicked, validation is applied to the text box but the form remains unchanged (still ng-valid). Subsequently, clicking the button triggers the function call despite the presence of validation requirements.

If the validation class is manually added without initiating the function call, the form starts off as invalid on page load and becomes valid once the text box is filled - demonstrating the expected behavior.

This behavior appears to stem from the dynamic injection of validations. It seems that the form's validations need to be reset after such injections take place.

The checkbox utilizes the iCheck Plugin with a directive:

angular.module('app').directive('checkValidation2', ['$compile',
function($compile) {
    return {
        restrict: 'A',
        require: '?ngModel',
        compile: function(ele, attr, ngModel) {
            ele.closest('form').validationEngine();
            //Removing directive attribute to prevent an infinite loop during DOM compilation

            ele.removeAttr("check-Validation2");
            var compile = $compile(ele); //Compile object during prelinking phase
            return function(scope, element, attrs, ngModel) {
                compile(scope); //Compile DOM during postlinking phase
                scope.$watch(attrs.ngModel, function(newValue, oldValue) {
                    var valid = !element.validationEngine('validate');
                    ngModel.$setValidity(element.context.name, valid);
                    return valid;
                });
            }

        }
    };
}

]);

Answer №1

When utilizing controllerAs syntax, ensure that your value is bound inside a scope instead of being outside.

$scope.$watch(angular.bind(this, function () {
    return this[attrs.ngModel]; // Evaluate ng-model value from `this`
}), function (newVal, oldVal) {
     var valid = !element.validationEngine('validate');// Check if the control is valid
     ngModel.$setValidity(element.context.name, valid); // Set validity accordingly 
     return valid;
});

Note:

To accurately reflect changes in the DOM, consider injecting form validationEngine during the compilation phase of the directive.

Directive:

.module('app').directive('checkValidation2', [
    function() {
        return {
            restrict: 'A',
            require: '?ngModel',
            compile: function(ele, attr, ngModel) {
                ele.closest('form').validationEngine();
                
                ele.removeAttr('checkValidation2'); // Remove directive attribute to prevent an infinite loop
                
                var compile = $compile(ele); // Compile object on prelink state
                return function(scope, element, attrs, ngModel) {
                    compile(scope); // Compile DOM in postlink phase
                    
                    scope.$watch(attrs.ngModel, function(newValue, oldValue) {
                        var valid = !element.validationEngine('validate'); // Check if the control is valid
                        ngModel.$setValidity(element.context.name, valid); // Set validity accordingly 
                        return valid;
                    });
                }

            }
        };
    }
]);

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

showing the response message from a post request using Vue.js and Axios

Within APIService.js, there's a function: createPatient(data){ const url = 'http://192.168.1.3/api/clinic/patient/add/'; return axios.post(url, data).then(resp => {return resp}); } In the script tag of my vue component: result ...

Utilizing JSON data in JavaScript to populate a datatable

After receiving a JSON result from an AJAX jQuery call, I stored it in a variable and attempted to insert the JSON data into a datatable. However, instead of inserting the data from the variable as intended, the datatable is currently populated with JSON d ...

JavaScript Promise Handling: using fetch method to retrieve and extract the PromiseValue

I am currently struggling to access the [[PromiseValue]] of a Promise. However, my function is returning a Promise instead and what I really want myFunction to return is the value stored in [[PromiseValue]] of the promised returned. The current situation ...

Utilizing in-app purchases within an Ionic Android app with the cordova-plugin-inapppurchase plugin

I am currently working with the Ionic framework to develop an Android application, and I'm looking to incorporate in-App-Purchase functionality. I followed the instructions provided in this link for writing the code. However, I encountered an error wh ...

How is the script type "text/html" utilized in contemporary applications? Is this specific example regarded as effective usage?

Is it considered good practice in today's standards to utilize something like the following code snippet and use jQuery to swap out content based on a selector? <script type="text/html" id="this-content1"> <h1>This Header Info One</h1& ...

What methods can be used to get npx to execute a JavaScript cli script on a Windows operating system

The Issue - While my npx scaffolding script runs smoothly on Linux, it encounters difficulties on Windows. I've noticed that many packages run flawlessly on Windows, but the difference in their operations remains elusive to me. Even after consulting A ...

Utilizing an Angular foreach loop for restructuring JSON data

I currently have an ng-repeat function that outputs arrays of objects in the following format: [ {"day":"10","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}, {"day":"3","title":"day","summary":"summary","description" ...

Tips for closing the stdio pipes of child processes in node.js?

Looking to spawn a child process from node.js and monitor its stdout before closing the pipe to terminate the node process. Here's my base code snippet that is currently not ending the node process: const childProcess = require("child_process"); con ...

Leveraging the power of React's callback ref in conjunction with a

I'm currently working on updating our Checkbox react component to support the indeterminate state while also making sure it properly forwards refs. The existing checkbox component already uses a callback ref internally to handle the indeterminate prop ...

AngularJS enhanced dropdown navigation bar built using Bootstrap styling

I'm currently learning how to implement Bootstrap, but I've run into an issue. I created a dropdown in the navigation bar, but when I clicked on it, the dropdown didn't collapse as expected. The class="dropdown" didn't change to class= ...

Performing a PHP Curl request and an ajax query to an ASP.NET page

I am attempting to send an ajax query to an ASP.NET page. Here is the algorithm I am following: 1. There is a form on my webpage; 2. When the user fills in all the fields, they click the submit button; 3. Upon clicking the submit button, JavaScript sends ...

Troubleshooting problem with strokeRect on canvas following a CSS transform rotate(90deg)

English is not my strong suit, so please bear with me. Let me outline the issue I'm currently grappling with. I'm in the process of developing a function that allows users to draw a rectangle on a canvas using their mouse (specifically, using t ...

Unable to insert a CodeSandbox iframe within a Docusaurus document

Having trouble identifying the reason behind it, I managed to successfully embed a YouTube video iframe. However, when attempting to do the same with a CodeSandbox iframe, a build error keeps occurring preventing it from working. Could there be some limi ...

Limiting Node.js entry with Express

I have a node.js script running on a server. I want to prevent it from being accessed directly from a browser and restrict access to only certain domains/IP addresses. Is this achievable? ...

What is the best way to securely store the OAuth access_token to be used at a later time?

My current challenge involves getting and storing an access token from the Pocket API using Node.js. I have successfully obtained the request token, redirected to the Pocket login page, returned to my site, and exchanged the request token for an access tok ...

What is the best way to ensure that this encompassing div adjusts its width to match that of its child elements?

My goal is to keep fave_hold at 100% of its parent div, while limiting the width of .faves to fit its child elements. These elements are generated dynamically with predefined widths. Below is the code snippet in React/JSX format: <div id='fave_h ...

Framer Motion's AnimatePresence feature fails to trigger animations when switching between pages

I'm running into issues with the Framer Motion library, specifically with the AnimatePresence transition. I've managed to make it work in normal situations, but when I encapsulate my Routes within a custom implementation, the exit animation fails ...

How to incorporate a JavaScript file into a Handlebars template

I am having trouble receiving calls to my JavaScript file. What could be the issue? Using MVC. Here is the code in view file, file.hbs: <div class="container"> <h2 onClick="test()">Title</h2> {{>list}} </div> <script sr ...

What is the solution to preventing contentEditable="true" from inserting <div> instead of <p> when the return key is pressed?

I have a div <div contentEditable="true"> <h1> My headline</h1> </div> When editing the text inside the <h1> tag and pressing return, a new div is added underneath instead of the usual paragraph tag. Resulting in: < ...

Issue encountered while running the TestCafe Docker Image within a GitLab CI job. Attempting to run automated end-to-end tests on BrowserStack

We are currently attempting to execute end-to-end tests using testcafe on BrowserStack triggered by a gitlab CI job. Unfortunately, an error keeps appearing: Error: spawn /home/user/.browserstack/BrowserStackLocal ENOENT Our approach involves implementin ...