Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating a percentage variable. No decimal points, No negative numbers

Tags:

javascript

This sounds easy but unable to get it to work. I need to accept a percentage number from 0 to 100 with no decimal numbers, no negative numbers. How can I do this validatation?

if ((Pcomplete == "" ) || (Pcomplete < 0 && Pcomplete > 100)) {
  alert('Percentage field is required. You need to type a number between 0 and 100');
  return false;
}
like image 599
Baba Avatar asked Dec 08 '25 07:12

Baba


2 Answers

this will always validate what you want, of course assuming it's a string when provided. Othwerise do value = "" + value or smth.

if (/[0-9]/.test(value) && parseInt(value) > 0 && parseInt(value) < 101) {
   // it IS a number, AND its value is between 0 and 100
}

Only allow numbers and only numbers between 0 and -100

the regex invalidates comma and dots etc.

like image 59
Mathijs Segers Avatar answered Dec 09 '25 19:12

Mathijs Segers


A Mod check will work to make sure that the variable is a whole number:

If Pcomplete % 1 == 0, then it is not a decimal number. Also, the vairbale cannot be both over 100 and less than 0, so seperate them with a ||.

if ((Pcomplete == "" ) || (Pcomplete < 0) || (Pcomplete > 100) || (PComplete % 1 !==0) {
  alert('Percentage field is required. You need to type a whole number between 0 and 100');
  return false;
}
like image 34
kittenchops Avatar answered Dec 09 '25 19:12

kittenchops



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!