JavaScript function to validate percentages

I am looking to create a function that will determine whether a given value is a percentage. The function should return true for numbers followed by a '%' symbol or decimal values representing percentages.

Here's how I want it to work:

/* input value ... return value */
percentage_check("21%") == true
percentage_check("21") == true
percentage_check("0.21") == true
percentage_check(21) == true
percentage_check(0.21) == true

percentage_check(121) == false //numbers above 100%
percentage_check(1.21) == true
percentage_check("twenty") == false

How should this function be implemented?

function percentage_check(n) {
 //code
}

Answer №1

Below is a valid solution:

function validate_percentage(input) {
 if(input.toString().match(/^\d+\.?\d?\d?%?$/) && parseFloat(input)<=100 && parseFloat(input)>=0){
    return true;
 }
 return false;
}

https://regex101.com/r/tY4vB6/2

Answer №2

function validate_percentage_input(input) {
    return (('' + input).match(/^\d+\.?\d*%?$/) || false) && parseFloat(input) >= 0 && parseFloat(input) <= 100;
}

document.write(validate_percentage_input("21%") + '<br>'); // == true
document.write(validate_percentage_input("21") + '<br>'); // == true
document.write(validate_percentage_input("0.21") + '<br>'); // == true
document.write(validate_percentage_input(21) + '<br>'); // == true
document.write(validate_percentage_input(0.21) + '<br>'); // == true
document.write(validate_percentage_input(121) + '<br>'); // == false // input cannot exceed 100%
document.write(validate_percentage_input(1.21) + '<br>'); // == true
document.write(validate_percentage_input("twenty") + '<br>'); // == false
document.write(validate_percentage_input("21Eur") + '<br>'); // == false

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

Components for designs using Meteor and Blaze

Hello, currently I am working with Meteor and Blaze. Here is how my routes are set up: FlowRouter.route('/software', { name: 'software', action(params, queryParams) { BlazeLayout.render('App_body', {main_ ...

Guide on deleting a record in a Mysql database using Codeigniter(3) without the need to refresh the page

I'm currently trying to delete a record from a MySQL database table using jQuery with Codeigniter(3). Despite it being a simple task, I am facing some challenges as I am new to both Codeigniter and jQuery. This is a section of the view where I need t ...

Unexpectedly, Ajax call is triggering additional callbacks

I am currently facing an issue with my AJAX request in the code below. The Chrome Inspector is showing that the callback function associated with the request is being called twice, resulting in the response being logged into the console twice. Additional ...

TensorflowJS Error: The property 'fetch' cannot be read as it is undefined

I am working on an Angular 7 application and attempting to load the mobilenet model by following the instructions in this example. To do this, I first installed tensorflowjs using the command npm install @tensorflow/tfjs (based on the steps provided in th ...

Populate an empty value in a key-value pair by using the subsequent value

Replace an empty value in a key-value pair with the first value of the next key. myitems = { 'items1': [{first:true, second:false}, {first:true, second:true}], 'items2': [], //should be filled with {first:true, second:false} 'it ...

The issue of child component experiencing multiple re-renders

In my application, I have a child component named Plot.js. This component accepts a prop called plot, which is an object containing a property called points that holds an array of x, y points. Additionally, there is an array named files. Each file in the f ...

Running both the React FrontEnd and NodeJs Backend on a single server

I have developed a full-stack application using React for the frontend and server.js written in nodejs(Express), with Postgres as my database backend. I have previously deployed a similar setup on Heroku, where I hosted my site. The difference is that on H ...

Encountered an error while reloading the page: "Unable to read property 'ArtisanID' of undefined."

Every time I refresh the page, an error pops up saying: Cannot read property 'ArtisanID' of undefined. Any suggestions on how to troubleshoot this issue? I'm relatively new to this framework and my intuition tells me that the component ins ...

Tips for adjusting the height of a Safari extension during runtime

After successfully developing a Safari extension, I am facing an issue with adjusting the width and height of the popover dynamically at runtime. Can anyone provide insights on how to modify the dimensions of the popover based on its content? ...

Loop through a collection of unique identifiers for documents and establish event listeners in Firestore

Within my Vuex store, there is an action designed to retrieve a list of uids for followed users from the current user's Firestore UserDataCollection document. The action then processes each uid to extract data that will be displayed on the UI. While t ...

In JavaScript, how does the usage of parentheses change the functionality of a function?

function find() { console.log("Request handler 'find' was called."); } function display() { console.log("Request handler 'display' was called."); } exports.find = find; exports.display = display; There ...

How can I place a THREE.ArrowHelper on a specific layer in Three.js?

Exploring the world of Three.js, I'm striving to understand how to organize elements onto separate layers. One of the challenges I'm facing involves an ArrowHelper that I've set up and added to the scene in the following manner: var ar ...

What is the best way to retrieve the present value of an input that belongs to an array of objects?

Struggling with populating an array with data and encountering a specific issue. 1 - Attempting to determine an index for each key in the array of objects, but encountering an error when a new input is added dynamically. The inputs are successfully added ...

Decipher complex JSON structures

I am working with a multi-level JSON structure: { "1":{ "name":"PHP", "slug":"/tag/php", "type":"Tag" }, "2":{ "name":"JavaScript", "slug":"/tag/javascript", "type":"Tag" }, "3":{ ...

Steps to open specifically the WhatsApp application upon clicking a hyperlink, image, or button

I need a code for my HTML website that will open the WhatsApp application when a user clicks on a link, image, or button while viewing the site on a mobile device. Only the WhatsApp application should be opened when a user interacts with a link on my webs ...

When using Node Puppeteer, if the page.on( "request" ) event is triggered, it will throw an error message stating "Request is already being handled!"

I am currently utilizing puppeteer-extra in conjunction with node.js to navigate through multiple URLs. During each iteration, I am attempting to intercept certain types of resources to load and encountering the error below. PS C:\Users\someuser ...

Postponing the execution of a controller until all JSON files have been fully loaded

I am currently trying to grasp the concepts of AngularJS, so my question might not be perfect. Is it feasible to delay the execution of a controller until the json files are fully loaded in a separate function? Below is the controller code: app ...

Is there any specific reason not to use a short HTML/CSS syntax like <div a b c></div>?

When it comes to writing HTML in less standard environments, such as a phonegap app where strict syntax and semantics are not crucial, I have developed a unique approach that works for me. I aim to keep my HTML code short and concise by using the followin ...

Checking for correct format of date in DD/MM/YYYY using javascript

My JavaScript code is not validating the date properly in my XHTML form. It keeps flagging every date as invalid. Can someone help me figure out what I'm missing? Any assistance would be greatly appreciated. Thank you! function validateForm(form) { ...

What is the best way to prevent the table from being added again once it has been displayed?

I'm faced with the task of displaying an HTML table in a popup window when a button is clicked, using Bootstrap modal functionality. This scenario is similar to a preview function where user input is displayed in a table when a preview button is click ...