Best way to validate a string in js - javascript

I need to make sure that my string is a number and for doing that, I was using isNaN function and everything was working but I got a problem when I typed in my input field '0e1'.
I was wondering what's the best way to check if my string is a number and without scientific notation

Try using regex. Here are some examples. The result is null if no match was found.
alert("0e1".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // null
alert("1".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // 1
alert("-1".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // -1
alert("1.0".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // 1.0
alert("-1.5".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // -1.5
alert("-1.5 4".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // null

If you want your input to only be an integer or float do this instead;
var input = '0e1';
if(!isNaN(input) && (parseInt(input, 10).toString() == input || parseFloat(input).toString() == input)){
//This is a valid number
}

Actually, the method you are using is fine. You have one problem with your code:
isNaN() should be !isNaN(). Remember, isNaN() checks if the number is NotaNumber. `!isNaN() checks if it IS a number.
isNaN(0e1) should return false because 0e1 is a number! I know, it's kind of confusing.
!isNaN(0e1) will return TRUE because !isNan() checks if a value IS a number.
I hope this helps.

isNaN() function determines whether a value is an illegal number, so if it is not a number. The good thing about isNaN function is, that is suportet by all browsers (ch, ie, ff, op, sf).
function myFunction() {
var a = isNaN(123) + "<br>";
var b = isNaN(-1.23) + "<br>";
var c = isNaN(123-456) + "<br>";
var d = isNaN("Hello") + "<br>";
var e = isNaN("2014/11/19") + "<br>";
var result = a + b + c + d + e;
document.getElementById("test").innerHTML = result;
}
So result would be: If value is a number return "False" if is not a number return "True".
You can test it on JsFiddle: isNaN()

Related

How to test if a string is a not number

I'm trying to verify if a string is text or number.
Could not find a proper way to verify.
Could you please advice?
Here is my problem:
var myNumber = "006";
var myText = "1. This is not a number";
isNaN(myNumber); // false
isNaN(myText); // false
I tried also:
isNaN(myNumber.split('.')[1]); // true
isNaN(myText.split('.')[1]); // true
parseInt(myNumber); // 6
parseInt(myText); // 1
What I would like to achieve would be to find when a string can be converted to a number (see myNumber). In case that the string is actually a text, how to spot it with javascript?
Could you please advise?
If I understood your question correctly I may have a solution but this will work even if the string is a number so here you go:
var yourNumber="55";
if(yourNumber*1==yourNumber){
alert("It's a number");
}else{alert("it's not a number");}
If parseInt() is not working for your desired results, you can try Number constructor. It gives you NaN for non-numbers, which you can verify by using isNaN() function.
var myNumber = "006";
var myText = "1. This is not a number";
console.log( Number(myNumber) );
console.log( Number(myText) );
Or you can use regular expressions:
var myNumber = "006";
var myText = "1. This is not a number";
var numRegex = /^\d+$/;
console.log( numRegex.test(myNumber) );
console.log( numRegex.test(myText) );
You can use regex.
function isNumber(num){
return /^(\d+)?(\.)?\d+$/.test(num);
}
isNumber("006") // true
isNumber(".6") // true
isNumber("1 not a number") // false
isNumber("23.63") // true
isNumber("23.6.3") // false
You can check if text is a number using isNaN function:
var myNumber = "006";
var myText = "1. This is not a number";
console.log(myNumber + ': ' + !isNaN(myNumber));
console.log(myText + ': ' + !isNaN(myText));
var reg = new RegExp('^[0-9]*$');
var myNumber = "006";
var myText = "1. This is not a number";
reg.test(myNumber) //true
reg.test(myText) //false
The short story:
I would really use the typeof operator.
From isNaN() | JavaScript MDN:
The isNaN() function determines whether a value is Not-A-Number or not. ... you may alternatively want to use Number.isNaN(), as defined in ECMAScript 6, or you can use typeof to determine if the value is Not-A-Number.
Long story:
Tried the following in a node console.
A NaN also results from attempted coercion to numeric values of non-numeric values for which no primitive numeric value is available.
isNaN(123) // false
isNaN(true) // false
isNaN("123") // false
isNaN({}) // true
isNaN(undefined) // true
In comparison to the global isNaN() function, Number.isNaN() doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to NaN, but aren't actually the same value as NaN. This also means that only values of the type number, that are also NaN, return true.
Number.isNaN(undefined) // false
Number.isNaN({}) // false
Number.isNaN(true) // false
Number.isNaN(123) // false
Number.isNaN(NaN) // true
Number.isNaN(0/0) // true
The typeof operator returns a string indicating the type of the unevaluated operand.
typeof(123) // number
typeof("123") // string
typeof(true) // boolean
Generally, the isNaN is the right idea, but you should parse it first:
var myNumber = "006";
var myText = "1. This is not a number";
Number.isNaN(Number.parseInt(myNumber)); // false
Number.isNaN(Number.parseInt(myText)); // true

Validating a data input javascript

I have been looking to validate the data input to check whether it is a integer or a string. I looked around and saw some suggestions and typeof suggestions but nothing seems to work.
var nam = prompt("Enter name:")
person.push(nam);
var mk1 = prompt("Enter mark 1:");
var mk1 = parseInt(mk1);
mark1.push(mk1);
If you want to check whether input string is not a number try this:
if (isNaN(parseInt(name, 10)) {
//name is String
} else {
//name is Number
}
use the === operator as below
if (mk1 === parseInt(mk1 , 10))
alert("mk1 is integer")
else
alert("mk1 is not an integer. May be String")
If you don't know that the argument is a number-
function isInt(n){
return Number(n)===n && n%1===0;
}
Try this way to find input type;
if(!isNaN(parseInt(mk1)))
// for integer
else if(!isNaN(parseFloat(mk1)))
//for float
else
// String
When you prompt() the user for data, you always get a string. If you want to check, whether it actually contains just a number, you can try this:
var value = prompt('...'),
num = parseInt(value, 10);
if (num == value) {
// ... it is an integer, use `num`
} else {
// ... it's not an integer (or not *just* an integer), use `value`
}
(or use parseFloat(value) for real numbers).
It's hard to say what are you trying to do really. You seem to declare var mk1 twice, which looks a bit strange. Also, even if parseInt fails (then returns NaN [Not a Number]) you add it to mark1, which is probably not what you want. Have a look at this:
var nam = prompt("Enter name:")
person.push(nam);
var mk1 = prompt("Enter mark 1:");
mk1 = parseInt(mk1);
if (Number.isNaN(mk1) === false) {
mark1.push(mk1);
} else {
alert("mark 1 is not a number");
}
Use this function:
isNaN(parseInt(mk1))
It will return "true" if not a number, and "false" if a number

Javascript Simple Addition Tool - NaN

I'm trying to make a simple addition tool to add 2 values together, I'm just having a little trouble with the NaN checking... would like to print "Please insert numbers only" if either A or B, or both are NaN.
function getTotal() {
var a = parseInt(document.addBoxes.boxA.value);
var b = parseInt(document.addBoxes.boxB.value);
if (total != NaN) {
total = a+b;
document.getElementById("total").innerHTML = "The sum is " + total + ".";
}
else if (a === NaN || b === NaN){
document.getElementById("total").innerHTML = "Please insert numbers only.";
}
else if (a === NaN && b === NaN){
document.getElementById("total").innerHTML = "Please insert numbers only.";
}
};
Also, if there is a performance-friendly way to do this, or a better method.
Thanks!
Checking each individual value for NaN is not required.
function getTotal() {
var a = parseInt(document.addBoxes.boxA.value);
var b = parseInt(document.addBoxes.boxB.value);
var total = a + b;
if (!isNaN(total)) {
document.getElementById("total").innerHTML = "The sum is " + total + ".";
} else {
document.getElementById("total").innerHTML = "Please insert numbers only.";
}
}
Several problems in your code.
Line 4: if (total != NaN) {
total hasn't been defined yet. You should define it in a var beforehand if you don't want to leak globals.
var total = a + b;
Also, NaN will never equal itself so this kind of equality is dangerous. Either use the built-in isNaN() function to check for NaN or (since you mentioned performance-friendly) you can skip the function invocation and use:
if (total !== total) {
Since NaN is the only thing in javascript that doesn't equal itself. Notice I'm using a strict not-equals, we don't want any coercion. This might be a bit too abstract and people who look at the code later (including yourself) might have forgotten this unique property of NaN so I'd prefix this conditional with a comment and perhaps a link to the MDN - Necessity of isNaN page.
Your code might end up looking something like simonzack's answer.

using an if statement to check if NaN

I'm getting a numeric value from a form. Then I check to see if it's NaN. If it is a number I want to set that value to a variable. The problem is that when I enter a valid number I still get an alert and the number isn't passed to the variable "date". How should I modify my statement so that when it is a valid number I can assign it to the variable date?
var adate = document.getElementById("dueDate").value;
if ( adate == NaN || " ") {
alert("Please enter a due date");
return;
}
else {
var date = (new Date()).setDate(adate);
}
processDate(date);
Use Javascript's isNaN() function.
Checking equality with NaN is always false, as per IEEE's standards.
Stephen Canon, a member of the IEEE-754 committee that decided this, has an excellent answer explaining this here.
As strange as it seems, NaN !== NaN.
if (adate !== adate || adate !== " ") {
//...
}
The isNaN function would work in a lot of cases. There is a good case to be made that it is broken, though.
One nice way of getting around this is:
MyNamespace.isNaN = function (x) {
return x !== x;
}
you could Use if( isNaN(adate))
good luck
You have two problems here. The result is that the conditional will always pass. This is what it does:
adate == NaN // first, test if adate == NaN (this always returns false)
|| // if the first test fails (i.e. always), carry on checking
" " // test if the string " " is truthy (this always returns true)
The || does two separate checks. It does not test to see if adate is "either NaN or " "", which seems to be what you expect.
Your code might as well say
if ( true ) {
You would be able to sort this out, however, if you tried two comparisons:
if ( (adate == NaN) || (adate === " ")) {
As other people have said, however, this doesn't work, because NaN !== NaN. So the solution is to use isNaN:
if (isNaN(adate) || (adate === " ")) {
By using isNaN method we can verify if the given input is number or not.
let num1 = parseInt(prompt('Enter your number-1'));
let num2 = parseInt(prompt('Enter your number-2'));
alert(num1 + " is of type " + typeof num1 + " & " + num2 + " is of type " + typeof num2);
if (isNaN(num1) || isNaN(num2)) {
alert("Can not add incompatible types");
} else {
let sum = num1 + num2;
alert("Sum is " + sum);
}

Round the value in Javascript

I have scenario where if user enters for example 000.03, I want to show the user it as .03 instead of 000.03. How can I do this with Javascript?
You can use a regular expression:
"000.03".replace(/^0+\./, ".");
Adjust it to your liking.
This actually is trickier than it first seems. Removing leading zero's is not something that is standard Javascript. I found this elegant solution online and edited it a bit.
function removeLeadingZeros(strNumber)
{
while (strNumber.substr(0,1) == '0' && strNumber.length>1)
{
strNumber = strNumber.substr(1);
}
return strNumber;
}
userInput = "000.03";
alert(removeLeadingZeros(userInput));
How about:
function showRounded(val) {
var zero = parseInt(val.split('.')[0],10) === 0;
return zero ? val.substring(val.indexOf('.')) : val.replace(/^0+/,'') );
}
console.log(showRounded('000.03')); //=> ".03"
console.log(showRounded('900.03')); //=> "900.03"
console.log(showRounded('009.03')); //=> "9.03"
Or adjust Álvaro G. Vicario's solution to get rid of leading zero's into:
String(parseFloat("090.03")).replace(/^0+\./, ".")
This function will take any string and try to parse it as a number, then format it the way you described:
function makePretty(userInput) {
var num,
str;
num = parseFloat(userInput); // e.g. 0.03
str = userInput.toString();
if (!isNaN(num) && str.substring(0, 1) === '0') {
str = str.substring(1); // e.g. .03
} else if (isNaN(num)) {
str = userInput; // it’s not a number, so just return the input
}
return str;
}
makePretty('000.03'); // '.03'
makePretty('020.03'); // '20.03'
It you feed it something it cannot parse as a number, it will just return it back.
Update: Oh, I see If the single leading zero needs to be removed as well. Updated the code.
Assuming your input's all the same format, and you want to display the .
user = "000.03";
user = user.substring(3);
You can convert a string into a number and back into a string to format it as "0.03":
var input = "000.03";
var output = (+input).toString(); // "0.03"
To get rid of any leading zeroes (e.g. ".03"), you can do:
var input = "000.03";
var output = input.substr(input.indexOf(".")); // ".03"
However, this improperly strips "20.30" to ".30". You can combine the first two methods to get around this:
var input = "000.03";
var output = Math.abs(+input) < 1 ?
input.substr(input.indexOf(".")) :
(+"000.03").toString();

Categories