r/shittyprogramming • u/YM_Industries • Apr 15 '21
Useful function for validating that a number falls within a range
Today I needed to check if the number a user entered into a textbox was between "0" and "999". The below code yields the correct result for any value that I could think to test. (Empty string is treated as valid, since "required" is a different validation step)
function validateRange(value, minimum, maximum) {
for(let i = 0; i < value.length; i++) {
if(value[i] < minimum[i]) {
return false;
}
if(!(value[i] <= maximum[i])) {
return false;
}
}
return true;
}
I hope you find this function useful in your own projects.
45
Upvotes
19
u/[deleted] Apr 15 '21
There should be a language flair on this sub
6
u/Palcikaman Apr 15 '21
Input and button should be in a form, and the validation should be on the form submit. This way I can't even press return to check if my number is valid or not
4
u/creepyswaps Apr 15 '21
It really is shitty. Why even have a minimum value? I went into your demo and changed the minimum to "10", entered 3 and it completely failed. I assume it's because your for() loop starts at 0 instead of minimum. And there should be some other value which is the maximum - minimum to get number of times to iterate through. I don't even know. This makes my brain hurt, even ignoring the overall algorithm design. Good job.
-1
u/f3xjc Apr 15 '21
Browser can do that work for you.
<input type="number" min="1" max="999" />