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

Employing the new operator in conjunction with a variable

Is there a way to achieve the following scenario: var foo = function(){ this.value = 1; } var bar = "foo"; var baz = new bar(); alert(baz.value) // 1 Specifically, I am looking for a method to instantiate an object using its string name. Any sugge ...

The React application is unable to communicate with my Express application in a production environment, despite functioning properly during development

Currently, I am attempting to make a basic get request to my express backend located at mywebsite.com/test. The expected response from the server should be {"test": "test"}. While this is working perfectly fine in development on localho ...

Any ideas for handling ProtractorJS timeouts while clicking an element?

The Issue at Hand I am currently facing a challenge with clicking a straightforward 'New Booking' button in my Angular 5 Material 2 Application. The code snippet for the button is as follows: <button _ngcontent-c9="" class="mat-menu-item" ma ...

Exploring ways to assign a value to an HTML element utilizing Jquery in combination with ASP.NET MVC 4 complex model information

Within an ASP.NET MVC 4 view, I am utilizing data from a Model to populate various HTML elements. The model is used in the view to showcase values like: <div>@Model.Category.Name</div> etc... However, there is a specific div tag <div id="D ...

Tips for positioning a sticky div underneath a stationary header

I'm currently utilizing Bootstrap 4 for my project, and I am encountering an issue with maintaining a div that has the class "sticky-top" just below a fixed navbar. Despite attempting to use JavaScript to replace the CSS while scrolling, it hasn' ...

Utilize React JS to parse and display a sophisticated JSON structure in a dropdown menu

Looking at the backend data structure provided, we have information on various courses in different departments. { "courseDetails" : [{"departmentId" : 105654, "courses" : [{"stream" : "science","courseIds" : ["104","105 ...

Tips on retrieving PHP variable values along with HTML response using AJAX in PHP

I am looking to retrieve 2 variables: 1) The total number of records from the mysqli query performed in search_members.php 2) A boolean value indicating whether any results were found Below is the code I have written: <input type="button" value="Sea ...

Prevent a <span> element from affecting the linking functionality of an <a> tag

Is it possible to make a hyperlink clickable without including the <span> tags within it and instead attaching a jQuery event to those tags? This is the code I'm using. It utilizes bootstrap's list-group for a navigation element: <ul cl ...

Unusual occurrence in Chrome when checking definitions: ReferenceError: x is not defined

Recently, I've come across some odd behavior in Chrome following its latest update. Whenever I try to determine if a variable is defined, it ends up triggering an uncaught error like the one shown below: if(x) { alert('x is defined.'); } T ...

What is the best way to dynamically adjust the select option?

I need help with handling JSON objects: [ { id: "IYQss7JM8LS4lXHV6twn", address: "US", orderStatus: "On the way", }, ]; My goal is to create a select option for the order status. If the current status is "On ...

Implement the usage of plainToClass within the constructor function

I have a dilemma with my constructor that assigns properties to the instance: class BaseModel { constructor (args = {}) { for (let key in args) { this[key] = args[key] } } } class User extends BaseModel { name: str ...

Refresh the vue-chart component in a nuxt.js application

I'm currently working on a nuxt project and I need to incorporate some charts into it. I'm using vue-chartjs as a plugin for this purpose. However, the issue I'm facing is that the chart data is fetched after the chart has already been drawn ...

Display the entire HTML webpage along with the embedded PDF file within an iframe

I have been tasked with embedding a relatively small PDF file within an HTML page and printing the entire page, including the PDF file inside an iframe. Below is the structure of my HTML page: https://i.stack.imgur.com/1kJZn.png Here is the code I am usin ...

Tips for utilizing the standard search functionality of Select2 while also implementing a remote data source

Even though I am able to populate the dropdown from the data source, there is an issue with filtering the results using the search field at the top. If I make an AJAX request to the API, fetch the data, create <option> elements for each result, and a ...

Fetch several images simultaneously from a photo collection using JavaScript by generating a batch process

I need help with creating an image gallery that allows users to download multiple images by selecting them. The download should result in a zip file. I have checkboxes for selecting the images, but I'm struggling to figure out how to enable the downlo ...

Choosing Drop Down Options Dynamically with Jquery

I have a total of 4 Drop Downs on my page. https://i.stack.imgur.com/6tHj5.png Each drop-down initially displays a "--select--" option by default. Additionally, each drop-down has a unique ID assigned to it. The second drop-down is disabled when the abov ...

Adding a class using jQuery based on whether a section is visible or hidden on the screen

Seeking advice on the best approach to take. Division 1 or section - Apply style 1 if division 1 is currently visible on the screen. Division 2 or section - Apply style 1 if division 2 is currently visible on the screen. Division 3 or section - Apply st ...

What method does jqGrid use to dynamically update the selection options list based on the status data?

Currently, I am utilizing jQgrid for displaying a list with data retrieved through Ajax. The list is displaying properly without any issues. However, my challenge lies in dynamically populating the list of options based on the status value received. Area ...

Choosing a populated control using JavaScript results in an empty value

Within my ASP.NET applications, I incorporate a server-side HTML select control. <select id="CompanyDropDown" runat="server" style="width:330px"> </select> To populate and pre-select items in this control, I use a JavaScript function triggere ...

Fixed: Transmitting user's verified email from website to chrome extension

I am currently in the process of developing a website named websiteA using Laravel 8 and Vuejs, along with a Chrome extension that utilizes JavaScript for web scraping. This extension is designed to extract content from another websiteB, and my goal is to ...