Automatic capitalization feature for input fields implemented with AngularJS

I have integrated a directive into my input field to validate a license key against a server-side API. While this functionality works well, I also want the license key to automatically add hyphens and appear in capital letters.

For example, when a user inputs abcd1234qwer5678, it should display as ABCD-1234-QWER-5678. (I am focusing on achieving auto-capitalization first, then I will work on adding hyphens).

I have attempted a few approaches. Initially, I tried using a $watch function within the controller:

$scope.$watch('licenceKey', function (newValue, oldValue) {
    $scope.$apply(function () {
        $scope.licenceKey = newValue.toUpperCase();
    })
});

Additionally, I explored using a second directive applied to the input:

myApp.directive('capitalize', function() {
   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {
        var capitalize = function(inputValue) {
           if(inputValue == undefined) inputValue = '';
           var capitalized = inputValue.toUpperCase();
           if(capitalized !== inputValue) {
              modelCtrl.$setViewValue(capitalized);
              modelCtrl.$render();
            }         
            return capitalized;
         }
         modelCtrl.$parsers.push(capitalize);
         capitalize(scope[attrs.ngModel]);  // capitalize initial value
     }
   };
});

The first approach doesn't seem to have any effect, while the second one replaces the existing text after a brief delay. The HTML for my input field is as follows:

<input type="text" name="licenceKey" ng-model="licenceKey" 
    ng-model-options="{ debounce : { 'default' : 150 } }" licence-key-validator />

What is the most effective way to achieve the desired outcome, and what could be causing these challenges?

I have noticed that when using Batarang to inspect the scope, the licenceKey remains null until I submit the form. Why isn't it being populated as I type into the input field?

angular.module('licenceApp.controllers', [])
    .controller('licenceController', ['$scope', 'licenceAPIservice', '$filter', function ($scope, licenceAPIservice, $filter) {
        $scope.licenceKey = "";

        $scope.$watch('licenceKey', function (newValue, oldValue) {
            $scope.$apply(function () {
                $scope.licenceKey = newValue.toUpperCase();
            })
        });
        ...

Update

I just realized that when using the watch method, the text doesn't get capitalized until a valid license key (validated by the licenceAPIservice) is entered. However, it does capitalize correctly when entering a lowercase valid key. See the code snippet below:

angular.module('licenceApp.directives', [])
    .directive('licenceKeyValidator', function ($http, $q, licenceAPIservice) {
        return {
            require: 'ngModel',
            link: function ($scope, element, attrs, ngModel) {
                ngModel.$asyncValidators.licenceKeyValidator = function (licenceKey) {
                    var deferred = $q.defer();

                    licenceAPIservice.validateKey(licenceKey).then(function (data) {
                        if (data.data) {
                            deferred.resolve();
                        }
                        else {
                            deferred.reject();
                        }
                    }, function () {
                        deferred.reject();
                    });

                    return deferred.promise;
                };
            }
        }
    });

Answer №1

I have successfully developed a compact function by utilizing a custom filter that both capitalizes and hyphenates. Feel free to review the code below and let me know if it aligns with your requirements.

http://plnkr.co/edit/u6NTYRakWbojg3pQxzkH?p=preview

Code:

var app = angular.module("myApp", []);

app.controller('myCtrl', ['$scope', '$filter', function($scope, $filter){

  $scope.myText = "";

  $scope.update = function(){ 
    $scope.myText = $filter('myFilter')($scope.myText); 
  };

}]); 

app.filter('myFilter', function(){
  return function(text){
    if(!text)
      return text;
    else{
      var processedText = text;
       processedText = processedText.toUpperCase().replace('', '');
      if(processedText.length > 4 && processedText[4] !== "-") 
        processedText = processedText.substring(0, 4) + "-" + processedText.substring(4);
      if(processedText.length > 9 && processedText[9] !== "-") 
        processedText = processedText.substring(0, 9) + "-" + processedText.substring(9);
      if(processedText.length > 14 && processedText[14] !== "-") 
        processedText = processedText.substring(0, 14) + "-" + processedText.substring(14); 
      return processedText; 
    }
  }; 
});

HTML:

<input ng-model="myText" ng-change="update()"/>

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

Assign a value to a HubSpot hidden form field by utilizing Javascript

I have a snippet of JavaScript code placed in the head section of my website: <!-- Form ID Setter --> <script> document.querySelector('input[name=form_submission_id]').value = new Date(); </script> My objective is to automat ...

To enable communication between methods, you can easily add a property to a JavaScript class component

Is there a better way to communicate between methods in a class? class T extends React.Component { constructor(props) { super(props) this.a = false; } methodA { //will set 'a' in this method, maybe async. } ...

What is the best way to create a linear flow when chaining promises?

I am facing an issue with my flow, where I am utilizing promises to handle the process. Here is the scenario: The User clicks a button to retrieve their current position using Ionic geolocation, which returns the latitude and longitude. Next, I aim to dec ...

Electron JS-powered app launcher for seamless application launching

Currently, I am working on a project to develop an application launcher using HTML, CSS, and JS with Electron JS. Each application is linked through an a href tag that directs users to the respective application path. If a normal link is used in the a hr ...

What is the best way to manage a vuex dispatch response?

Despite feeling like the answer is right in front of me, I'm waving the white flag and seeking suggestions. The challenge lies in my login form that submits to an AWS API and reacts to the result. The trouble starts when the handleSubmit method is tr ...

Is there a way to present both Javascript and templates from parallel directories using express?

QUERY: Is there a way to modify the server.js file so that the three.js script in index.html does not display an error message like Cannot GET /node_modules/three/three.js? Code Snippet: index.html <!DOCTYPE html> <html lang="en"> <head&g ...

Unlocking the Secrets of Laravel Blade Integration in a Script File

I am attempting to create a customized store locator application using the guidance provided in this useful tutorial on Google Maps and Laravel 5. While going through various queries related to integrating Google Maps with Laravel, I came across these info ...

Efficiently organizing items within a list on Ionic

Currently, I have an ion-list structured as follows: <ion-list *ngFor = "let chat of Chats"> <ion-item (click) = "openChat(chat.id)"> <ion-label> <h2> {{chat.username}} </h2> ...

Creating a dynamic overlapping image effect with CSS and JavaScript

My fullwidth div has an image that overlaps it. When the browser is resized, more of the image is either shown or hidden without resizing the actual image itself. I managed to get this effect for the width, but how can I achieve the same result for the hei ...

Is Angular capable of displaying a date within a specific timeframe using ng-show?

So I have a button that, when clicked, displays a list of data. I am adding a unique font awesome icon in there if the JSON key value exists. However, here lies the issue. The particular key happens to be a date. I need my ng-show function to check whether ...

Steps to remove a package from the npm registry

Is it feasible to eliminate or erase a complete module from the npm registry? Please be aware that using npm -f unpublish does not permit the deletion of packages older than 24 hours. ...

Guide on incorporating arrays into an array using JavaScript

Is there a way to achieve the specified outcome in JavaScript? I attempted to find a method for it on MDN but was unsuccessful. let a, b let allNumbers = [] for (a = 10; a < 60; a = a + 10) { for (b = 1; b <= 3; b++) { allNumbers.push(a ...

Processing MongoDB elements in NodeJS by retrieving them and appending them to a list or array for further processing

Currently, I am involved in a full stack project that requires fetching stock data from mongodb and performing algorithms on specific information. Here is an illustration of the JSON object stored in mongodb: [{ _id: 5e11d67abf05f3d00d56b801, LUNA: { ...

Submitting form by double clicking and pressing enter at the same time

When using jQuery Validate to validate forms, I encounter a problem where double-clicking the submit button results in my application making two entries with the same data. This issue also occurs when pressing enter multiple times. Despite researching dif ...

How can you use $_REQUEST in PHP to fetch an array of inputs for database insertion?

I have a webpage where I am utilizing AJAX to transfer inputs to a PHP file for database entry. The following is my JavaScript code: var pageLoaded = function () { var submitButton = document.getElementById("submit"); if (submitButton) { submitButton. ...

How to italicize a portion of output using JavaScript

There are numerous inquiries on the internet and on this site regarding how to make italic fonts, however, none specifically address how to italicize only a section of a string. In my scenario, I have a form where I input the book title, author's nam ...

Does SameSite=Lax grant permission for GET requests from third-party sources?

After exploring the MDN documentation on SameSite=Lax, I have come to understand the following: In modern browsers, cookies can be sent along with GET requests initiated by a third-party website or during top-level navigations. This is the default behav ...

`Warning: The alert function is not working properly in the console error

I am currently working on integrating otp functionality into my Ionic 3 project. I am facing an issue where I am able to receive the otp, but it is not redirecting to the otp receive page due to a specific error. Below is the console error that I am encou ...

Activate JavaScript functions by pressing the enter key, allowing for various searches, AJAX requests, and DataTable displays to occur seamlessly without the need to refresh

I recently developed a web page that integrates an AWS API interface to interact with an RDS Aurora MySQL Serverless database. Users can input a SQL statement and click the Query button, which triggers an AJAX request, returns JSON data, and converts the d ...

Unable to capture screenshot of hovered element using Cypress

Having an issue with taking a screenshot of an element with a hover effect. The screenshots always come out without the hover effect applied. tableListMaps.lineWithText('Hello world', 'myLine'); cy.get('@myLine').realH ...