Form validation numeric range (minimum/maximum) in JavaScript - javascript

Have a script that defines text as being a number using a regular expression:
function validateTextNumericInRange(textInputId)
{
var numRegex = /^[\d]+$/;
var textInput = document.getElementById(textInputId);
var valid = true;
if (numRegex.test(textInput.value) == false) {
alert('Value must be a number between 3-48');
valid = false;
}
return valid;
}
Need to use this format and provide a min/max range (arbitrary for now, say between 3 and 48). How would I modify this regex to complete and have a correct argument?

I don't understand your question. Do you mean that you want a number that is between 3 and 48 digits, or that the value of the number must be between 3 and 48?
For the latter you don't need a regex:
function validateTextNumericInRange (textInputId) {
var textInput = document.getElementById(textInputId);
var value = parseInt(textInput.value, 10);
return (!isNaN(value) && value >= 3 && value <= 48);
}
A more generic solution:
function validateTextNumericInRange(textInputId, min, max) {
var textInput = document.getElementById(textInputId);
var value = parseInt(textInput.value, 10);
return (!isNaN(value) && value >= min && value <= max);
}
To test to see if a number is between 3 and 48 digits long, you can use the regular expression /^[0-9]{3, 48}$/.

A regular expression would be hard and inflexible, and for your example it would be:
/^(?:[3-9]|[1-3][0-9]|4[0-8])$/
Better go with Vivins' solution.

I'm not a good JavaScript developer, but I know that in Java you can use this syntax to test for minimum and maximum length:
[1-9][0-9]{2,4}
[1-9][0-9]{min,max}

function isInteger(value) {
if ((value.toString()).replace(/^-\d|\d/, "").length == 0) {
return true;
}
return false;
}
function integerInRange(value, min, max) {
if (isInteger(value)) {
if (parseInt(value, 10) >= min && parseInt(value, 10 <= max)) {
return true;
} else {
return false; // Not in range
}
} else {
return false; // Not an integer
}
}
integerInRange( 55, 3, 48); // Returns false
integerInRange("55", 3, 48); // Returns false
integerInRange( 25, 3, 48); // Returns true
integerInRange("25", 3, 48); // Returns true
In your case you would need to call it this way:
integerInRange(document.getElementById(textInputId).value, 3, 48);

Related

How does the modulus operator handle strings in Javascript

I know how modulus works in general, but it is not clear to me how the operator handles strings.
Recently, I had to write a script which checks if a name (string) contains an even number of letters. This actually worked, using modulus 2 and checking if result was 1 or 0:
function isNameEven(firstName) {
if (firstName % 2 === 0) {
return true;
}
else {
return false;
}
}
So I'm assuming the letters in the string were counted?
The result is always NaN
const oneLetter = "a";
const twoLetters = "ab";
const threeLetters = "abc";
console.log(oneLetter % 2);
console.log(twoLetters % 2);
console.log(threeLetters % 2);
Your function doesn't work if you pass it a string that can't be implicitly converted to a number that isn't NaN.
function isNameEven(firstName) {
if (firstName % 2 === 0) {
return true;
} else {
return false;
}
}
const oneLetter = "a";
const twoLetters = "ab";
const threeLetters = "abc";
console.log(isNameEven(oneLetter));
console.log(isNameEven(twoLetters));
console.log(isNameEven(threeLetters));
You could check the length property of the string though.
function isNameEven(firstName) {
if (firstName.length % 2 === 0) {
return true;
} else {
return false;
}
}
const oneLetter = "a";
const twoLetters = "ab";
const threeLetters = "abc";
console.log(isNameEven(oneLetter));
console.log(isNameEven(twoLetters));
console.log(isNameEven(threeLetters));

Elegant solution for determining which range a numeric value falls into

If I supply a number to a function, how would I go about validating it against a range of numbers like this?
1-10 = A
11-20 = B
21-30 = C
...
I know I can do if statements to evaluate this, but I'm looking for something more elegant because the problem gets a lot more complex and I don't want a nasty web of ifs.
var letter = "";
function getLetter(num) {
if (num >= 1 && num <= 10) {
letter = "A";
} else if (num >= 11 && num <= 20) {
letter = "B";
}
// this eventually gets gross
}
Expected outcome of getLetter(14) would be "B", and getLetter(49) would be "E", etc. Case/switch is also off the table for similar reasons.
Any other ideas welcome.
Just a point about your code
function getLetter(num) {
if (num >= 1 && num <= 10) {
letter = "A";
} else if (num >= 11 && num <= 20) {
letter = "B";
}
// this eventually gets gross
}
this can be simplified to
function getLetter(num) {
if (num >= 1) {
if(num <= 10) {
letter = "A";
} else if (num <= 20) {
letter = "B";
}
// this eventually gets gross too
}
}
But:
If it's as simple as every letter represents a range of 10 values:
function getLetter(num) {
return String.fromCharCode(65 + Math.floor((num - 1) / 10));
}
console.log(getLetter(1));
console.log(getLetter(14));
console.log(getLetter(49));
or as suggested
function getLetter(num) {
const ret = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
return ret[Math.floor((num - 1) / 10)] || "+"; // greater than 260
}
console.log(getLetter(1));
console.log(getLetter(14));
console.log(getLetter(49));
console.log(getLetter(261));
function getLetter(number) {
let ranges = {
a: 10,
b: 20,
c: 30,
underflow: 0,
overflow: Infinity
}
return Object.entries(ranges)
.sort(([ka, va], [kb, vb]) => va - vb) // because object key sort order isn't guaranteed
// though it will be in the order as declared, but
// sorting makes sense
.find(([key, value]) => number <= value)[0];
}
console.log(getLetter(5))
console.log(getLetter(17))
console.log(getLetter(20))
console.log(getLetter(30))
console.log(getLetter(31))
console.log(getLetter(0))
If the ranges are contiguous, you only need one of the boundaries
Works alright if you want to put your ranges into an object, and then loop through that
function getLetter (number) {
let ranges = {
a: [1, 10],
b: [11, 20],
c: [21, 30],
d: [31, 36],
e: [37, 40]
}
return Object.keys(ranges).find((key) => {
let currRange = ranges[key];
if (number >= currRange[0] && number <= currRange[1]) {
return key;
}
});
}
console.log(getLetter(5))
console.log(getLetter(17))
console.log(getLetter(20))
console.log(getLetter(30))
console.log(getLetter(35))
console.log(getLetter(39))

Why does function return undefined when it explicitly is told to return true?

I was trying to solve the following coding exercise.
We have two special characters. The first character can be represented
by one bit 0. The second character can be represented by two bits (10
or 11).
Now given a string represented by several bits. Return whether the
last character must be a one-bit character or not. The given string
will always end with a zero.
example:
Input: bits = [1, 0, 0] Output: True
Below is my solution for the above challenge. Why is this returning undefined? If I use [1,0,1,0] as input, it should return true but I am getting undefined. I am explicitly writing true in the return statement and not the results of a variable.
var isOneBitCharacter = function(bits) {
console.log(bits);
var length = bits.length;
if (length == 1) {
return true;
}
if (length == 0) {return false;}
if (length == 2 && bits[0] === 1) {
return false;
}
if (bits[0] === 1) {
isOneBitCharacter(bits.slice(1));
} else {
isOneBitCharacter(bits.slice(2));
}
};
isOneBitCharacter([1,0,1,0]);
I guess you are missing returns. Here is adjusted code:
var isOneBitCharacter = function(bits) {
console.log(bits);
var length = bits.length;
if (length == 1) {
return true;
}
if (length == 0) {return false;}
// added return here and next statements
if (length == 2 && bits[0] === 1) {
return false;
}
if (bits[0] === 1) {
return isOneBitCharacter(bits.slice(1));
} else {
return isOneBitCharacter(bits.slice(2));
}
};
isOneBitCharacter([1,0,1,0]);

javascript limit on positive and negative number with delimiter comma based onkeyup and onkeypress

Today i have problem in delimiting number for negative and positive number. For example, i have a textbox to insert my number and the result after write the number. Suddenly the number is separated with comma delimiter like this either the number is positive or negative
eg : 1000 -> 1,000
-1000 -> -1,000
-1000.12 -> -1,000.12
-0.00001 -> -0.00001
How to achieve this using javascript, what i know is using onkeypress and onkeyup. Thank you very much :)
This is not the best solution, but you can implement this according to your need.
var msg = document.getElementById('myInputBox'),
numberPattern = /^[0-9]+$/;
msg.addEventListener('keyup', function(e) {
msg.value = getFormattedData(msg.value);
});
function checkNumeric(str) {
return str.replace(/\,/g, '');
}
Number.prototype.format = function() {
return this.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
};
function getFormattedData(num) {
var i = checkNumeric(num),
isNegative = checkNumeric(num) < 0,
val;
if (num.indexOf('.') > -1) {
return num;
}
else if (num[num.length - 1] === ',') {
return num;
}
else if(i.length < 3) {
return i;
}else {
val = Number(i.replace(/[^\d]+/g, ''));
}
return (isNegative ? '-' : '') + val.format();
}
<input type="text" id='myInputBox' value="" />

How do I write an if/else statement inside a function that tells me if a number is evenly divisible by 2 (in javascript)

I'm working through codacademy and I can't understand the help discussions in the forum.
This is what I have so far but it returns false when i run the function with an even number:
var isEven = function(number) {
if (isEven % 2 == 0){
return true;
}else{
return false;
}
};
You are performing the mathematical operation on isEven (the function itself). You need to check number:
var isEven = function(number) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
};
or better yet:
var isEven = function(number) {
return number % 2 === 0;
};
You could even do this, by making use of the truthy/falsy behavior of 1 and 0:
var isEven = function(number) {
return !(number % 2);
};
but I think the previous approach more clearly conveys how the logic works.
you can write this function as follows:
var isEven = function(number) {
return ((number % 2) == 0);
}
Your function is not working because you're checking against the function name, not the function parameter (number). Try this:
var isEven = function(number) {
return number % 2 == 0;
}
You doing it wrong in isEven itself..
Do it like..
var isEven = function(number) {
return number% 2 == 0;
}
Consider the following:
0 is considered to be false in Javascript.
1 is considered to be true in Javascript.
! makes false become true and vice versa.
The % operator can be used to keep higher numbers in a zero-to-one range.
Since 0 % 2 gives 0 (i.e. false) and 1 % 2 gives 1 (i.e. true), you simply need to invert the result with !:
function isEven(x) { return !(x % 2); }
console.log(isEven(0)); // true
console.log(isEven(1)); // false
console.log(isEven(2)); // true
console.log(isEven(3)); // false
Note that this could also be written as:
function isEven(x) { return (x % 2) == 0; }
...because:
0 % 2 is 0 (so it is true to say that it is equal to zero).
1 % 2 is 1 (so it is false to say that it is equal to zero).

Categories