Why does Javascript in Angular throw an exception when using value, match, and replace functions together?

I have a small JavaScript function that I would like to implement in an Angular service or controller.

function cprCheck(frm) {
var cpr = frm.cpr.value;
if (cpr.match(/[0-9]{6}\-[0-9]{4}/)) {
    cpr = cpr.replace(/\-/g, "");
    var chk = 0;
    for (i = 9; i > -1; i--) {
        chk += (+cpr.charAt(i)) * ((i > 2) ? (10 - i) : (4 - i));
    }
    if (chk % 11 == 0) return true;
}
return false;
}

When using the functions value, match, and replace, why am I getting an exception?

Answer №1

I approached the issue from a unique angle and came up with an alternative solution:

        var customValidationConfig = {
        verifyAlgorithm: true,
        idRegex: /^\d{10}$/,
        cleanUpRegex: /-/g,
        daysInVariousMonths: [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
        controlValues: [4, 3, 2, 7, 6, 5, 4, 3, 2, 1] // source: http://da.wikipedia.org/wiki/CPR-nummer#Kontrol_af_personnummer
    };

    var evaluateModulus11 = function (value) {
        var parts = (value + '').split('');
        var controls = customValidationConfig.controlValues;
        var total = 0;

        angular.forEach(parts, function (currentValue, index) {
            var currentControlValue = controls[index];
            total += currentValue * currentControlValue;
        });

        return total % 11 === 0;
    };

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

Disabling Navigation with Arrow Keys in Prettyphoto

Is there a way to prevent arrow keys from functioning in PrettyPhoto for a specific instance? I have tried using keyboard_shortcuts:false, but it still reloads the frame if left or right arrow keys are pressed, causing the form inside to reset. However, co ...

Navigating through an object using both dot and bracket notation

Can anyone shed some light on why I keep getting an 'undefined' message when trying to access object properties using dot notation like return contacts[i].prop;? However, if I use bracket notation like return contacts[i][prop];, it works fine an ...

Efficient communication in Angular: Sharing data among controllers and components

Recently joining a new project, I am faced with the task of implementing a small feature. In my setup, there are 2 distinct views: Cars.html and Wheels.html The Cars.html view is associated with the controller Cars.controller.js On the other hand, the W ...

AngularJS $HTTP service is a built-in service that makes

I am facing an issue with pulling the list of current streams from the API and iterating that information with AngularJS. I have tried inputting the JSON data directly into the js file, and it works fine with Angular. However, when I use an http request as ...

Node receiving empty array as result after processing post request

My current task involves testing the post method on Postman. Strangely, every time I post the result it shows an empty array []. Upon further investigation by console logging on the node side, it also returns an empty array. CREATE TABLE users ( user_ ...

React Hooks: In useEffect(), unable to modify parent component's state

Within my component, I have a form for users to input a title, description, and images. This component is nested within its parent component, and I want the form data to be saved if the user switches sections and returns later without losing their progress ...

Conceal a particular object from view by selecting it from the menu

I want to hide a specific element when the burger button is clicked. (See CaptureElementNoDisplay.PNG for the element to hide) When I click the burger button again to close the menu, I want the hidden item to be displayed once more. I've successfull ...

An issue arises with Angular ui-router when attempting to transition while clicking a link within ui-grid

I am currently utilizing angular's ui-grid to showcase a table of facilities. My goal is to have the facility name link to its respective page with the facility id when clicked. Within my columnDefs I have the following setup: columnDefs = [ { ...

The best method for quickly loading a webpage that is over 20MB in size

My website is a single-page calendar featuring a full year's worth of images. With 344 requests and a total load size of 20MB, the page consists of a simple PHP script without a database. The requests include a CSS file (15KB), 4 JS files (20KB), two ...

Creating a binary tree in vanilla JavaScript and styling it with HTML and CSS

I'm facing a challenge with my homework. I am required to convert my JavaScript binary tree into HTML and CSS, strictly using vanilla JavaScript without any HTML code. I have the tree structure and a recursive function that adds all the tree elements ...

Unable to retrieve object element in angular

weatherApp.controller('forecastController', ['$scope','weatherService','$resource','$log', function($scope,weatherService,$resource,$log){ var cnto =3; $scope.forecastholder = weatherService.holder; $scope ...

Convert the jade file to an HTML file while keeping the original file name

I'm currently attempting to configure Jade in a way that allows me to save my Jade files as HTML files while retaining the same file name. For example, I would like the file views/index.jade to be saved as dist/index.html This should apply to all ad ...

What is the best method to verify a string against a set of approved characters using JavaScript?

I have written some code that sanitizes user input to allow only alphanumeric characters and hyphens. Here is the code snippet: https://jsfiddle.net/py4pnr0L/ const inputValue = 'GHJHlk;sxa787BVK'; const sanitizedValue = inputValue.toLowerCase( ...

Preventing Angular button click when an invalid input is focused out

Here is a Plunker link http://plnkr.co/edit/XVCtNX29hFfXtvREYtVF?p=preview that I have prepared. In this example, I've asked you to: 1. Enter something in the input field. 2. Click directly on the button without interacting with any other element. ...

Tips for sending data to CSS in Angular

I have an Angular application where I need to calculate the width of an element and store it in a variable called finalposition. Then, I want to move this element to the left by (finalposition)px when hovering over it. How can I achieve this styling effect ...

Determine total and showcase it as the range slider is adjusted

Seeking to calculate and present the result of three range sliders. The equation I aim to showcase is: KM driven per year * Avg KM/100L / Price of fuel I have managed to display each slider's individual values, but I am uncertain about how to show t ...

Adjust the width of a container to exceed 32767 using jquery in the Opera browser

I am looking to create a compact timeline using jQuery, and I want this timeline to have a width exceeding 32767 pixels. Interestingly, when I attempt to modify the width using the jQuery code $(".timelinecontainer").width(32767);, it doesn't seem to ...

The functionality to disable and reenable a button after performing a calculation is not functioning properly in the code

Here's the issue I'm facing with my code: When I click the search button, a for loop prints "hi" 5000 times. Before this loop starts, I want to disable the button. However, after the console.log is done, the button should be enabled again. But fo ...

The powerful combination of knockout.js, breeze, and dynatree/fancytree offers a dynamic and

This concept is really challenging for me to grasp as I am not accustomed to this particular style of programming or data management. Presently, my main objective is to pass a JSON object retrieved through Breeze into a Dynatree or Fancytree. All the ava ...

Internet Explorer causing issues with Jasmine mocking ajax calls

Recently, I attempted to develop a spec that enables mocking out Ajax calls. The testing procedure functions seamlessly on browsers such as Chrome and Firefox; however, I encountered some difficulties while executing the test case on Internet Explorer (spe ...