Incorporating multiple true statements into an IF ELSE structure can enhance the decision-making

I'm struggling with getting a true return value for numbers that are integers and have either 4 or 6 digits - no decimals or letters allowed. The issue seems to be the validation of whether it's really a number and if it has a decimal point.

Although I believe I have applied the right functions, I can't seem to properly connect them to my if statement. I want to check if three different conditions are true before returning true, but I haven't quite figured it out yet.

If possible, please only provide a hint, a link, SUDO Code, or references I can explore. I'll follow up with the answer once I've solved it myself.

JS

function validatePIN (pin) {
  //return true or false
   var result = (pin - Math.floor(pin)) !== 0; 
   if( pin.length === 4 || isNaN(pin) || result) {
     return true
   } else if ( pin.length === 6 || isNaN(pin) || result) {
     return true
   } else return false
}

Thanks

Answer №1

A straightforward regular expression can be implemented to verify whether a string consists of either 4 or 6 numbers.

function isValidPin (pin) {
   return /^(\d{4}|\d{6})$/.test(pin.toString());
}

console.log(isValidPin(123));
console.log(isValidPin("1234"));
console.log(isValidPin("12345"));
console.log(isValidPin("123456"));
console.log(isValidPin("1234567"));
console.log(isValidPin("12.45"));
console.log(isValidPin("12e45"));

Answer №2

To determine if the conditions are met, you can use the AND operator (&&) in JavaScript.

function checkPasswordComplexity (password) {
  //return true or false
   var hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/.test(password); 
if( password.length >= 8 && /[0-9]/.test(password) && /[A-Z]/.test(password) && /[a-z]/.test(password) && hasSpecialChar) 
  { return true;} else { return false;}
}

Answer №3

In order to pass the validation, switch either your 'and' or'veriify my PIN code'

 function checkPIN (pin) {
     //output true or false
      var outcome = (pin - Math.floor(pin)) !== 0; 
     if( pin.length === 4 && isNaN(pin) && outcome) 
     { return true} 
     else if ( pin.length === 6 && isNaN(pin) && outcome)  {
     return true
    } else return false
    }

Answer №4

Give this a shot:

function checkPIN(pin) {
  var parsedNum = Math.parseInt(pin, 10);

  // checking if the input is not an integer
  if(pin !== parsedNum.toString()) return false;

  return pin.length === 4 || pin.length === 6;
}

Answer №5

It's possible that I am mistaken, but it might be worth considering checking if the length of the code is either 4 OR 6 before proceeding with your other validations:

function validatePIN (pin) {
    //return true or false
    var result = (pin - Math.floor(pin)) !== 0; 
    if(!isNaN(pin) && (pin.length === 4 || pin.length === 6) && result) {
        return true;
    } else {
        return false;
    }
}

Additionally, I have made some modifications to your code since it didn't make sense to return true for NaN values.

Answer №6

If you're looking for a solution, consider using regular expressions for ease of implementation.

console.log(445584, validatePin(445584));
console.log("445584", validatePin("445584"));
console.log("alj454", validatePin("alj454"));
console.log(4455.84, validatePin(4455.84));

function validatePin(pin){
  return /^(\d{4}|\d{6})$/.test(pin);
}

Answer №7

One solution is to utilize the isNaN() function in order to identify any non-numeric characters.

Additionally, consider converting the data to a string using .toString() so that you can easily determine its length with .length.

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

Stopping the loop: Disabling the SetInterval function with ResponsiveVoice code in JavaScript

Currently, I am developing a queuing system and implementing voice announcements using Responsive Voice. I have used setInterval, but the issue is that the voice keeps looping without stopping. $( document ).ready(function() { setInterval(function() ...

Variability in Focus Behavior while Opening a URL in a New Tab with window.open()

Here is a code snippet I have been using to open a URL in a new tab: window.open(urlToOpen, '_blank', 'noopener noreferrer'); The issue I am experiencing is that when this code is executed for the first time, it opens the URL in a new ...

Can a Singular Ajax Call be Configured for Multiple Inputs?

Within a PHP file, there is a form tag containing multiple inputs of type submit (essentially buttons) generated automatically by an external PHP script with names like button0, button1, etc. My goal is to utilize AJAX and jQuery to send the value of the c ...

What language should be used for JSON data formats?

I am dealing with a JSON file named myjson.cfg that has the following structure: { "values": { "a": 1, "b": 2, "c": 3, "d": 4 }, "sales": [ { "a": 0, "b": 0, "c": 0, "d": 0, ...

Unable to fetch data in CakePHP 3.x controller using jQuery AJAX POST

I've been searching everywhere and unfortunately, I can't seem to figure out why the data is not being sent to my controller when posting via ajax. Here's the jQuery code snippet: var newDate = {}; newDate['start' ...

Retrieve a JavaScript file located in a separate folder

I'm facing an issue with a project that has the following layout: project | - public | - -index.html src | - -index.js The code I am using to import the file is as follows: <script src="../src/index.js"></script> H ...

Is it possible for a popup to appear without any user interaction

Do you ever wonder how certain websites are able to trigger pop-ups without being blocked by Chrome's pop-up blocker? I had always thought that pop-up blockers only allowed window.open if it was initiated by a user action. However, the situation seem ...

Verify the position of the scrollbar without triggering any reflow

Here is a function I have: is_bottom: function() { if (settings.scrollBottomOffset === -1) { return false; } else { var scroll_height, scroll_top, height; scroll_height = ...

Automate your workflow with Apps Script: Save time by appending a row and seamlessly including additional details to the

I currently have 2 server-side scripts that handle data from an html form. The first script saves user input to the last row available in my Google sheet, while the second script adds additional details to the newly created row. Although both scripts work ...

Using JavaScript's regular expressions to identify a code block that commences with a specified pattern

Currently, I am working on a JavaScript script and I am in need of a Regex pattern to quickly match "JSDocs". The specific pattern that I am trying to match looks like this: # this is block1 /// text /// text /// text /// text # this is block2 /// text // ...

Adjusting the Transparency of the Background in a Pop-Up

I am experiencing an issue with my popup where I want the background to be transparent. However, when I set the opacity in CSS to 0.5 or less, the text also becomes transparent and very dark. How can I achieve a background with 50% opacity while keeping th ...

Spring MVC applications might experience slow loading times when loading RequireJS libraries

Recently, I integrated RequireJS into my Spring MVC application to manage dependencies for various libraries, including jQuery and jQuery UI. Although I have successfully implemented it, I am facing an issue whenever the page is loaded or refreshed. Initia ...

What is the best way to incorporate a CSS transition without any dynamic property changes?

Is there a way to add a transition effect to a header when its size changes without a specified height value in the CSS? The header consists of only text with top and bottom padding, so as the text changes, the height adjusts accordingly. How can I impleme ...

What is the best way to detect the window scroll event within a VueJS component?

Looking to capture the window scroll event in my Vue component. This is what I have attempted so far: <my-component v-on:scroll="scrollFunction"> ... </my-component> I have defined the scrollFunction(event) in my component methods, but it ...

Activate JavaScript validation

Within each section (displayed as tabs), I have a custom validator. When one tab is active, the other is hidden. To proceed to submission, I need to disable client validation for the inactive tab. I attempt to do this by calling ValidatorEnable(, false); ...

Understanding the Execution of Asynchronous Code

I've been grappling with this problem for a while now, but I just can't seem to find the solution. That's why I'm reaching out for your expertise. Consider the example below: const async = require('async') var counter = 0 v ...

retrieve the value obtained from a promise in an outer scope

I need a simple function that returns the name. Here's my existing code snippet: getName(entity, id) { const promise = userServices.getName(entity, id).then((data) => { return data; }); / ...

Guide to successfully integrate MathJax into your React application

I developed an application using HTML that successfully rendered MathJax equations through a script tag. However, after transitioning to React, the MathJax equations are no longer appearing. I have tried adding the MathJax script (shown below) in the comp ...

Enhancing the Appearance of Legends in Chartjs

I'm attempting to customize the legend in my Chartjs chart, but I'm facing an issue where I can't seem to change the font color. What I want to achieve is having the font color in white while keeping the individual item colors intact in the ...

What is the best way to define one API route that accommodates two different query combinations?

Is it possible to define 1 API route with 2 different query combination options? We have 2 routes: GET /api/v1/resource?filter=byName&key=restaurant&city=chicago GET /api/v1/resource?filter=byLocation&lat=34&long=78 In soaJS, schema ...