user4708518
user4708518

Reputation:

Javascript check if input is a percentage

Just wondering if anyone can let me know how I can check if input from a website is a percentage? i.e. 50%. So if this is true I can use another prompt telling them that it must be a percentage and ask them to re-enter.

Here is my Javascript code:

function changeprogressclient() {
    var howmuch = prompt("Please enter a custom percentage", "50%");
    document.getElementById('progbar').style.width = howmuch;
    $("#progressnumber").html(howmuch);
}

Thanks in advance.

Upvotes: 1

Views: 5341

Answers (2)

Nikas music and gaming
Nikas music and gaming

Reputation: 1282

I found a better solution that Paul's answer:

^(\d+|(\.\d+))(\.\d+)?%$
if (/^(\d+|(\.\d+))(\.\d+)?%$/.test(howmuch)) {
  // String is a percentage
}

it matches:

50%

50.5%

0.5%

.5%

Upvotes: 4

Paul S.
Paul S.

Reputation: 66334

You can test the String has a valid pattern using RegExp

if (/^\d+(\.\d+)?%$/.test(howmuch)) {
    // pass
} else {
    // fail
}

Regular expression visualization

Demo on Debuggex

Upvotes: 6

Related Questions