What steps do I need to take to transform this function into an Angular directive?

Is there a way to transform this function into an AngularJS directive for real-time validation of user input? I'm encountering an error when trying to use it as a regular function in the controller:

"Error: pesel.substring is not a function"

function decode(pesel) 
{
    var year=parseInt(pesel.substring(0,2),10);
    var month = parseInt(pesel.substring(2,4),10)-1;
    var day = parseInt(pesel.substring(4,6),10);

    if(month>80) {
        year = year + 1800;
        month = month - 80;
    }
    else if(month > 60) {
        year = year + 2200;
        month = month - 60;
    }
    else if (month > 40) {
        year = year + 2100;
        month = month - 40;
    }
    else if (month > 20) {
        year = year + 2000;
        month = month - 20;
    }
    else {
        year += 1900;
    }

    var birthday=new Date();
    birthday.setFullYear(year, month, day);

    var weights = [9,7,3,1,9,7,3,1,9,7];
    var sum = 0

    for(var i=0;i<weights.length;i++) {
        sum+=(parseInt(pesel.substring(i,i+1),10) * weights[i]);
    }

    sum=sum % 10;
    var valid=(sum===parseInt(pesel.substring(10,11),10));

    //sex
    if(parseInt(pesel.substring(9,10),10) % 2 === 1) { 
        var sex='m';
    } else {
        var sex='f';
    }

    return {valid:valid,sex:sex,date:birthday};
}

Answer №1

According to Abdo's explanation, it seems that the value passed to the function, pesel, may not be a string.

To address this issue, you should include the following line at the beginning of your function:

pesel = (pesel || '').toString();

This adjustment ensures that non-string values are handled correctly and guarantees that pesel is treated as a string moving forward.

Answer №2

To ensure the accuracy of input data, it is recommended to implement a parser/formatter combination or a dedicated validator.

Employ formatter/parsers when extracting birthday and gender information, with a validator in place for verification.

Regards

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

The function cannot be invoked. The 'Boolean' type does not have any call signatures. An error has occurred in the computed property of Vue3

Currently, I am working on creating a computed property that checks if an item is in the array. The function I have created returns a boolean value and takes one parameter, which is the item to be checked. isSelected: function (item: MediaGalleryItemTypes) ...

Using JQuery to loop through elements when clicked

I've been experimenting with different methods to iterate through a series of 4 li elements, each having a class of "item_n" where n is a number from 1 to 4. I want the iteration to increase by 1 with every click. Despite my efforts, my code isn' ...

The functionality in commands.js operates smoothly despite the absence of Cypress and cy being defined

When I input a custom command in commands.js, WebStorm's linter flags both Cypress and cy as undefined without providing any IntelliSense support. Oddly enough, these are properly defined in all integration files. In commands.js Cypress.Commands.add( ...

I'm curious why I need to add an extra await in my Vue.js unit test whenever multiple calls are made to my Firebase auth mock

In my vue.js application with firebase authentication, I encountered an issue while testing the Login.vue component. To mock firebase auth, I had to simulate the configuration file used for initializing firebase (named firebase.config). It's worth men ...

Navigating additional information in D3 Node Link Force diagram

Recently delving into the world of D3, I have been pleasantly surprised by its capabilities and decided to experiment with the Directional Force Layout. My Objective Initially, I successfully created a json object using a for loop to prepare my items for ...

Utilizing Puppeteer in JavaScript to loop through and iterate over a list of links

I am currently attempting to loop through a set of unique YouTube video links in order to capture screenshots. Upon further investigation, I discovered that the for loop below is spawning 2 separate process threads, one for each index i. The processALink( ...

What are the ways in which Angular can offer assistance to Internet Explorer 9?

The news is out - the Angular team has just announced their support for Internet Explorer 9! This revelation has left me wondering, how is it even possible? Currently, I am an avid user of AngularJS and have dedicated time to studying its ins and outs. Fr ...

Verifying the existence of an item without relying on expect statements

Once a user logs into my web application, the Sign Out link will appear - it is not displayed on the login page. When running my Protractor tests, I need to ensure that the user is logged in. This means that in my initial test, I must first log in. To det ...

Why does the method Array.concat on an extended class remove empty values in Node.js version 8.9.3?

I am experimenting with adding new functionality to Arrays in node.js without altering the original Array class to avoid any unintended consequences in other modules. During testing, I encountered some failures which led me to discover that the behavior o ...

Angular is displaying parentheses for negative numbers

When working on my template, I encounter a math issue where the result sometimes turns out to be a negative number. The problem is that when this happens, it displays the number within parentheses. How can I fix this using Angular 1.2? This is my controll ...

Issue with Struts 2 tag causing malfunction in validating the collection

When iterating through a list in a JSP file using Struts 2 tags, the code below is used: <%@ taglib prefix="s" uri="/struts-tags"%> <head> ... The issue arises with date validation. The following line of code does not work: <td><s:d ...

Automated Field Population: Harnessing jQuery Library to Fill in Multiple Fields Automatically

I have a specific code that is divided into multiple textboxes with set character limits. Each textbox holds a part of the code, and they need to be separated for different reasons. I am looking for a way to paste the entire code into the first textbox and ...

Generate unique identifiers to rotate images dynamically on the webpage

My goal is to rotate every image on a page, and while this works with a single image, it only rotates the first one since each ID needs to be unique. I need to find a way to dynamically increment the IDs as they are encountered on the page. Below is what I ...

Encountering an error while running a Meteor application with React: "Received an error stating that `something` is not defined when building the application or running with the `--production` flag."

Running my Meteor application locally on my PC with the meteor run command is no problem. However, when I try to build it using the following steps: cd ^project_path^ meteor build --directory ~/build I encounter an issue when testing the successful build ...

Node.js app experiencing intermittent issues with AngularJS interceptor failing to include JWT Bearer token in all requests

I have implemented a JWT authentication system in a node app. To ensure the Bearer token is included in every request, I used an interceptor. It functions correctly when accessing a restricted route within Angular or by using curl with the token specified ...

Struggling with navigating JSON data in JavaScript and facing difficulties sorting the array

I am currently facing the challenge of organizing data obtained from an API using JavaScript. JavaScript Code to Retrieve Data: function getResults() { var url = $.getJSON("http://api.api.com&leagues=SOCENGPRE&lang=en&format=jsonp&cal ...

Guide on accessing a variable by passing a partial name in a function

I need help with creating a function that can retrieve an object by name, using a partial input as the parameter. When I attempted to achieve this using the code snippet below, it returned undefined. Is there a way to successfully access a variable by pa ...

Error encountered: jQuery version 1.8.0 reports a syntax error due to an unrecognized expression containing ">" symbol

After adding jquery to my website, I encountered an issue with the jQuery 1.8.0 error: Error Message: Syntax error, unrecognized expression: &gt; Can someone please assist me with this problem? ...

What is the best way to refresh an Angular scope variable with data obtained from the Google Maps Places API?

I am looking to implement a feature where users can search for locations using the Google Places API. When they click on a specific location, I want to update a parameter value in the scope. Here is a visual representation: The Google integration works s ...

Leveraging assistance alongside grunt-static-handlebars

Looking for guidance on implementing custom helpers with grunt-static-handlebars. I've followed the documentation but can't seem to get it right. I have successfully created helpers for client-side handlebars and now want to use them server-side ...