Find the output using typeof function - javascript

I am writing a code. And here I have a problem how can I fix that. I have an input line, it takes a string or a number. So I need to check what is the output and get the answer. I need to give a simple solution. So I can't use functions or something like that.
let input = prompt('Enter your text.');
if (typeof input === "string") {
alert("You have string.");
} else if (typeof input === "number" && input > 30) {
alert("number more than 30");
} else if (typeof input === "number" && input < 30) {
alert("number less then 30");
}

prompt will always return a string.
If you want to check whether the string is composed purely of numerical values, you could use a regular expression:
if (/^[+-]?\d+(?:\.\d+)?$/.test(input)) {
// then it's purely numerical
const num = Number(input.trim());
// perform more operations on the number
} else {
// it's not composed of only numerical characters
}
If you don't want to use a regex, you can use Number alone, but then you'll also include values like Infinity which might not be desirable, and since Number('') gives 0, you'll have to check for that separately:
const num = Number(input);
if (input.trim().length && !Number.isNaN(num)) {
// then it's a number, use num
}
Another approach that I'd recommend is to avoid prompt entirely. Consider using a proper modal instead, such as a form with an input box and a submit button.
In such a case, if you want to require a numeric input, just do:
<input type="number">

I had a similar problem a few weeks ago and this is what I did:
function testNumber(test) {
if (isNaN(test) === false) {
console.log("this is a number");
} else {
console.log("this is not a number");
}
}
testNumber(4); // number
testNumber("4") // number
testNumber("string") // not a number
You can replace "test" for a variable if you don't want to use a function
if (isNaN(myVar) === false) {}
And you may want to add more checks if you want to differentiate between 4 and "4"

You can do
let input = prompt('Enter your text.');
if(isNaN(Number(input))){alert("You have string.")};
if (Number(input) > 30) {
alert("number more than 30");
} else if (Number(input) < 30) {
alert("number less then 30");
}
So it can change all Stringed-numbers to numbers and check if they are number with the isNaN function

Related

Javascript Eval() thinks first value is a function

I am writing a function that will evaluate expressions in an input field and return the sum.
Currently is working but I am running into an error that I just cannot figure out. Here is my code in Plunker.
function linkFunction(scope) {
var PO = 10;
scope.value = PO;
scope.result = '';
scope.Evaluate = function (input) {
if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
return alert("You must only use numbers, not letters")
} else if (input.match(/[!"^£$&[{}\]?\\##~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol
return alert("You must only use the symbols specified")
} else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
return alert("You can only use 1 decimal point")
} else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
return alert("You cannot put two decimals one after another")
}
// if (input.match(/\d*\(\d\W\d\)/g) != null){
// }
var percentPattern = /[0-9]*\.?[0-9]+%/g;
var expressionResults = input.match(percentPattern);
if (scope.enablePercentage) { //if parameter = 1, then do this code.
if (expressionResults != null) { //if user has entered into the input field
if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
return alert("Too many % values");
} else {// user has met all requirements
var percentageValue = parseFloat(expressionResults) * PO / 100;
input = input.replace(expressionResults, percentageValue);
}
}
} else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
return alert("You cannot use %");
}
scope.result = eval(input);
}
}});
If you write 10(5+3) it gives you an error
TypeError: 10 is not a function
Obviously if a user ran this code they would expect to see the value 80.
Eval thinks that 10() is a function.
Does anyone know how to fix this problem. Thanks
eval expects you to pass it JavaScript, not algebra.
If you want to multiply two values together then you must use a Multiplicative Operator.
10 * (5+3)

check if input form value (int) is less than expected

My question is about validating a form. I am doing a validation of two fields, one of them receives the value in decimal, example ($ 500.00), is already with mask.
In this field that receives the value, it can not be less than 300.00.
If it is smaller 300.00, a message will appear saying the value has to be greater than 300.00.
Summary: The validation checks that it is empty, but does not check if the (number) int is less than $ 300
I'm using it this way (there's more code, in short):
function valid_simulation(form1) {
if (form1.valor.value == ' ') {
alert("value is not valid");
return false;
}
if (form1.valor.value <= 300) {
alert("value is not valid");
return false;
}
}
Thanks for any help.
Your basic concept is correct: set the message when the if statement test is falsy. Something like the following:
function showFormError(message) {
$("#alertBox").text(message)
}
if (isInvalid) { showFormError("We have a problem.") }
If the dollar mark is the issue, You can split it and validate.
var userInput = $("#inputData").val();
if(userInput.includes("$")) {
var splitArray = userInput.split("$");
if (typeof splitArray[1] && parseFloat(splitArray[1]) < 300){
alert("Amount Not valid");
}
}

Javascript user input validation

My exercise is to force a user to type a number and check that it is less than 100. I think I've done this well but there is another case I don't know how to do. If the user does not type any number in the space, the program should show something like "you must type a number". How should I write the code?
var number=prompt('enter a number');
if (number<100){
newnumber=100-number;
document.write(number+'is less than 100 by'+ newnumber);
}else if(number>100){
document.write('type again');
}
You can determine if the users input is a valid number by using the isNaN function. I have also validated the blank character for you, as shown below.
var isValid = !isNaN(number) && number !== "";
Full snippet:
var number = prompt('enter a number');
number = number.replace(/\s/g, "");
var isValid = !isNaN(number) && number !== "";
if (isValid) {
if (number<100) {
newnumber=100-number;
document.write(number+'is less than 100 by'+ newnumber);
} else if(number>100) {
document.write('type again');
}
} else {
document.write("Looks like you didn't enter a valid number");
}
https://jsfiddle.net/ezgn5cv5/
var number = null;
while (number !== 0 && !number || number >= 100) {
number = parseInt(prompt('Enter a number, less than 100'));
}
document.write(
number +
' is less than 100 by ' +
(100 - number)
);
This puts us in a loop for whether or not the number is a valid integer (I assumed that's what you wanted, but you could change this to float or something else), and under 100. Only when the user's input is valid will it go to the line to output.
The second condition for the while loop is !number. This basically tests for falsy conditions, such as NaN or null. If parseInt() can't figure out what the user typed in for a number, it will return NaN. And, of course, we initialized the number variable to null.
The first condition for while is number !== 0 is actually required because of the second condition which tests for falsy. 0 is falsy, but 0 is a valid number less than 100, so we need to make sure that we let 0 be valid. Conditionals like these short circuit. That means that they are processed from left to right, and any condition failing the test will immediately bypass the conditional block of code below. If number is 0, we know that the whole condition is false and we can move on.
The third condition simply ensures we're under 100 by re-prompting if we're not.
Also, I should note that document.write() has some issues. It's better to select an element on the page and set its text.
Remove all spaces .replace(/\s/g, "").
Detect if user input a number using parseFloat() if you want to allow
user to input decimal numbers like 5.254 or only integers using
parseInt() like 5.
Then detect if number > 100 or number < 100.
See this example:
var number = prompt('enter a number');
number = number.replace(/\s/g, ""); //remove all spaces
if (number != "") { // if not empty
if (parseFloat(number) == number) { // if decimal/integer number
if (number < 100) {
newnumber = 100 - number;
document.write(number + ' is less than 100 by ' + newnumber);
} else if (number > 100) {
//number = prompt('enter a number');
document.write('type again');
}
} else {
//number = prompt('enter a number');
document.write('you must type a number');
}
} else { // if empty input
//number = prompt('enter a number');
document.write('shouldn\'t be empty');
}

How to tell if "123#231.23" is not a number in javascript?

parseInt("123#231.23") returns 123, which is a number.
There are tons of functions out there to detect if something is a number or not already, but they all depend on parseInt.
What is another generic way of detecting that this is not an integer without using regex?
if (isNaN("123#231.23"))
{
alert("IsNaN - not a number");
}
else
{
alert ("it is a number");
}
I'm assuming that OP need to distinguish if input is a number or not. If input is float or integer looks irrelevant to his problem.
Maybe, I'm wrong...
EDIT:
Alright, to keep everyone happy, integer in javasript is pretty big.
How big integer is in javascript check here.
Asking if something is integer is asking is it a whole number between 9007199254740992 and -9007199254740992. Wholeness of the number you may check using modulus %
$("#cmd").click(function (e) { ChectIfInteger( $("#txt").val() ) });
function ChectIfInteger(myval){
if (isNaN(myval)){
alert("not integer (not number)")
}
else{
//it is a number but it is integer?
if( myval % 1 == 0 ){
if (myval <= 9007199254740992 && myval >= -9007199254740992)
{
alert("it is integer in javascript");
}
else{
alert ("not integer");
}
}
else{
alert("nope, not integer");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt"/>
<input type="button" id="cmd" value="test input">
Convert back to String and compare:
String(parseInt("123"))=="123" // true
String(parseInt("123.sdfs"))=="123.sdfs" //false
If you really want to check "for valid integer" you must combine isNaN with something else like this:
function isValidInteger(numberToTest) {
return !(isNaN(numberToTest) || String(parseInt(numberToTest)) !== numberToTest.toString());
}
This will evaluate like:
console.log(isValidInteger('123#231.23')); // false
console.log(isValidInteger('123231.23')); // false
console.log(isValidInteger('12323')); // true
console.log(isValidInteger(1e-1)); // false
console.log(isValidInteger('1e-1')); // false
And this work even with numbers.
Here is PLNKR to test.
I think this is the best way to test for integers:
function isInt(str) {
if (typeof str !== 'number' && typeof str !== 'string') {
return false;
}
return str % 1 === 0;
}
Just note that strings / numbers like "123.0" evaluates to true.
Here's yet another one that doesn't rely on string stuff:
function looksLikeInteger(n) {
return +n == n && +n === ~~n;
}
Probably should be called "looksLikeJavaScriptInteger" because it only works for 32-bit integers. It coerces to numeric with unary + and then checks for equality (so ugly strings and objects are tossed out there) and then checks to make sure that the numeric value doesn't change when coerced to an integer.

Number Validation Not Working

I have an input field thats only supposed to take numbers inbetween 1 and 4. If the number is inbetween 1 and 4, it runs some code. If not, it shoots an alert that tells the user to try again with a number between 1 and 4. Here is my code
var number = document.getElementById("num").value;
if(Number(number) === 1 || Number(number) === 2 || Number(number) === 3 || Number(number) === 4 ){
//success code here///
}
else if(Number(number) !== 1 || Number(number) !== 2 || Number(number) !== 3 || Number(number) !== 4) {
} alert("Please type a whole number between(and including) 1 and 4 into the input field.");
I learned that the '.value;' function returns a string, even if the value is a number. So I put the var 'number' in the Number(); function that converts it to a number.
The problem is, when I type 1 into the input field. It shoots the alert even though it equals 1. None of the other numbers work either. I checked the console, and there are no syntax errors(also according to DreamWeaver). Help would be highly appreciated :)
I think you made a simple mistake of putting your alert outside the else if clause.
However there are a few other things you can do to make that a little more readable and efficient.
// Call Number() here so you only have to do it once
var number = Number(document.getElementById("num").value);
// You can also do something like parseInt(document.getElementById("num").value)
// Now check to see if Number() or parseInt() actually parsed an integer out of their input
// and then check that if it's outside your number range
if (isNaN(number) || number < 1 || number > 4) {
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
} else {
// Do Successful code
}
we can write like this also
var patt1 = /[1-4]/g;
if(patt1.test(number)){
//success code here///
}
else{
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
}

Categories

Resources