Create custom AngularJS directives for validation and store them in a variable

Through the use of AngularJS, I've developed a directive called "integer" that invalidates a form if anything other than integers are entered. Because I'm generating the page dynamically by fetching data from the database, it would be helpful to specify the type of validation as a variable and utilize this variable as the directive, which could be for integers, doubles, etc. To gain a better understanding, please refer to the following Plunker: http://plnkr.co/edit/QEqEexCzSDnUuuhnYpbN?p=preview

<form name="dynamicForm" ng-controller="Controller" ng-submit="applyConfiguration()">
    <my-customer info="component" name="{{dynamicName}}" ng-model="password" {{dynamicValidate}}></my-customer>
    <span class="error" ng-show="dynamicForm.{{dynamicName}}.$error.{{dynamicValidate}}">Not valid number!</span>
    <hr>
    <input type="submit" value='Apply'>
  </form>

(function(angular) {
  'use strict';
angular.module('docsIsolateScopeDirective', [])
  .controller('Controller', ['$scope', function($scope) {
    $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
    $scope.igor = { name: 'Igor', address: '123 Somewhere' };
    $scope.persons = [$scope.naomi,$scope.igor];
    $scope.password = "first password";
    $scope.component = 'text';
    $scope.dynamicName = 'testName';
    $scope.dynamicValidate = 'integer';
    $scope.applyConfiguration = function(){
      alert($scope.password);
    }
  }])
  .directive('myCustomer', function() {
    return {
      restrict: 'E',
      scope: {
        info: '=',
        ngModel: '='
      },
      template: function(elem,attr){
        //var template = 'Name: {{info.name}} Address: {{info.address}}';
        var template = '<input type="{{info}}" name="fname" ng-model = "ngModel">';
        //elem.html(template);
        return template;
      }
    };
  }).directive('integer', function (){ 
        return {
            require: 'ngModel',
            link: function(scope, elem, attr, ngModel) {
                var validator = function (value) {
                    //var num = parseFloat(value);

                     if(/^(\-|\+)?([0-9]+(\[0-9]+)?|Infinity)$/.test(value)){
                        ngModel.$setValidity('integer',true);
                        return value;
                    }else{
                        ngModel.$setValidity('integer',false);
                        return value;
                    }
                };
                ngModel.$parsers.unshift(validator);
                ngModel.$formatters.unshift(validator);
            }
        };
    });
})(window.angular);

Instead of using the attribute "integer," I aim to assign the already initialized variable dynamicValidate, set as "integer" in the controller. Best regards, Mukthi

Answer №1

Instead of using a direct integer validation, consider creating a more general directive for validation purposes and passing the specific validation requirements there.

For example:

<my-customer info="component" name="{{dynamicName}}" ng-model="password" validation="integer"></my-customer>

Then, create a directive named 'validation':

app.directive('validation', [function () {
  return {
    require: 'ngModel',
    link: function (scope, elem, attrs, ctrl) {

      scope.$watch('[' + attrs.ngModel + ', ' + attrs.validation + ']', function(value){
      if(value[0]=="integer")
        {
           //Your logic for integer here
         }
      }, true);

    }
  }

This approach is logically sound and should function correctly. Give it a try!

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

Customizing external elements with React's inline styling feature

Trying to use React to style elements generated by a third-party library has been a challenge. In the snippet below, I was able to achieve the desired styling using CSS, but now I am looking to accomplish the same using JavaScript. This way, users can defi ...

Ways to streamline redundant code by creating a higher order function that accepts different parameter types in TypeScript

Recently, I've been exploring the idea of refactoring this code into a higher order function using TypeScript to enhance its cleanliness and reusability. However, I'm facing quite a challenge in getting it to work seamlessly. import { DocumentDef ...

Navigating Google GeoChart Tooltips using Google Spreadsheet Data

My objective is to create a custom GeoChart for the company's website that will display data specific to each state in the US region based on team member assignments. The GeoChart should color states according to which team member helps that state&apo ...

What is the reason for IE displaying null when the model does not exist?

Why does IE 11 render 'null' if my model does not exist? For instance: <tr> <td [innerHTML]="model?.prop1 | my-pipe"></td> </tr> Imagine this scenario: When the page loads, a request is sent to the server and the res ...

Is the default behavior of Ctrl + C affected by catching SIGINT in NodeJS?

When I run my nodejs application on Windows, it displays ^C and goes back to the cmd prompt when I press Ctrl + C. However, I have included a SIGINT handler in my code as shown below: process.on('SIGINT', (code) => { console.log("Process term ...

Finding the height of concealed content within a div using the overflow:hidden setup

I'm trying to create a div that expands when clicked to reveal its content. I've taken the following steps so far: Established a div with overflow:hidden property Developed a JavaScript function that switches between a "minimized" and "maximize ...

What is the best way to merge javascript files and have them load after the page has already loaded on an asp.net site?

I recently came across a helpful SE Post that discussed combining external javascript files for better optimization, which is something I'm interested in. Following recommendations, I have converted internal javascripts into an external .js file and s ...

How can we add styles to text entered into a form input field in a targeted way?

Is there a way to apply styling to the second word entered into a form input text field after the user hits "enter" and the data is output? In this scenario, the text always follows the format of 3 numbers, followed by a space, and then a name. For examp ...

Attributes requested with jQuery JavaScript Library

Is there a way to dynamically add extra key-value pairs to the query string for all requests sent to the web server? Whether it's through direct href links, Ajax get post calls or any other method, is there a generic client-side handler that can handl ...

Component html element in Angular not being updated by service

Within my Angular service, I have a property linked to a text field in a component's HTML. Oddly, when this property is updated by the service, the new value doesn't reflect in the HTML element unless the element is clicked on. I'm perplex ...

Sending Grunt Jade configurations to a specific file

I'm currently using grunt-contrib-jade and I'm trying to utilize the pkg.name and pkg.version variables to generate my css file name. Unfortunately, I haven't been able to make this work on my own and would appreciate any assistance. Below i ...

How can I properly reset a timeout duration?

I'm currently working with a function that looks like this: function blabla(){ ... setTimeout(() => { //do some stuff }, 10000) } My question is, how can I reset the time of the timeout (10000) if the function was called and ...

Utilizing Immutable.js within React's Pure Components

Having some difficulty incorporating React PureComponents with Immutable.js. Take a look at this demonstration: https://codepen.io/SandoCalrissian/pen/QaEmeX The demo showcases 2 components being rendered. The first (NoramlPure) is a regular PureComponen ...

Encountering difficulties in loading my personal components within angular2 framework

I encountered an issue while trying to load the component located at 'app/shared/lookup/lookup.component.ts' from 'app/associate/abc.component.ts' Folder Structure https://i.stack.imgur.com/sZwvK.jpg Error Message https://i.stack.img ...

The jQuery AJAX delete function is only able to capture the initial form submission

I am facing an issue with making an AJAX call to a PHP file to delete a row in the database. The problem is that it only deletes the first row. Despite my extensive research on this matter, I have not been able to find a solution. Therefore, I am reaching ...

Detecting collisions between two squares in an HTML5 canvas

class Snake { constructor() { this.x = 400; this.y = 400; this.width = 25; this.height = 25; } draw() { ctx.fillRect(this.x, this.y, this.width, this.height); } } let snake = new Snake(); class ...

Utilizing Discord.js to enable a command for a particular channel

Running a Discord.js bot and struggling to figure out how to restrict the command! help to only the #commands channel. Already have the channel ID, so what steps should be taken in the command event to achieve this? Appreciate any guidance! ...

The importance of managing both synchronous and asynchronous processes in Javascript

As I delved into the intricacies of Javascript's asynchronous behavior within its single-threaded environment, I stumbled upon a comment that caught my attention regarding the following code snippet: request(..., function (error, response, body) ...

Leveraging Python to authenticate on a website using JavaScript and secure HTTPS connection

I am looking to utilize python for logging into a website that utilizes javascript and https encryption. The specific site I'm referring to is: My goal is to create a python script that successfully logs in, with the intention of later translating th ...

Error message: Unhandled error - $(...).sidr does not exist as a function. [Chrome developer console]

I included this code in the basic module HTML block of a WordPress page builder and encountered the white screen of death. According to the Chrome developer console, the following error occurred: helpers.js?ver=4.5.3:15 Uncaught TypeError: $(...).sidr is ...