Reputation:
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
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
Reputation: 66334
You can test the String has a valid pattern using RegExp
if (/^\d+(\.\d+)?%$/.test(howmuch)) {
// pass
} else {
// fail
}
Upvotes: 6