Get type of value entered - javascript

I have a small piece of code where I need to get the typeof value entered. Right now, i am getting only value entered in the box, but not the typeof. Can anyone help me here?
<p id="res">Value</p><input type="text" id="fname" name="fname"><br><br>
<script>
document.getElementById('fname').addEventListener('input', function(){
document.getElementById('res').textContent= this.value;
});
</script>

You need to use typeof keyword, and if you want to test number vs string then you need to do a check type by using isNaN and Number
I changed your function to arrow function
document.getElementById('fname').addEventListener('input', e => {
const value = e.currentTarget.value;
const checkType = isNaN(Number(value)) ? value : Number(value)
document.getElementById('res').textContent = typeof checkType
})
<p id="res">Value</p><input type="text" id="fname" name="fname"><br><br>

So typeof is not going to help you here. because the input is type="text" everthing typed into it will be casted to a string. exp: some types a 4, will be given to the js as "4". Im assuming you dont care about the type itself and just really want to know if they typed in a number. if thats the case, use the isNaN Function which will return false if a value can be casted to a number
isNaN("4") //false isNaN("hello") //true
PS: NaN stands for not a number

Related

Angular Validator check if input is number

I'm trying to perfom form validation in Angular 9 to check if the value of a certain input is a number (integer or decimal).
I therefore created the following custom validator:
import { AbstractControl, ValidationErrors } from '#angular/forms';
export class NumberValidator {
static number(control: AbstractControl): ValidationErrors | null {
if (typeof +control.value === "number") return null;
return { notANumber: "The value is not a number"};
};
}
It works fine for an integer or decimal input, telling my that it's valid, however it also tells me that the following string value for example "foo" is valid.
How can I fix that?
+ makes string as NaN which type of is number remove it. or if u have to check one more plus of number then
if (typeof +control.value === "number" && !isNaN(+control.value)) return null;
"+" convert variable to number ( +control.value )
So in your example you convert control.value to the number, and then check if this variable is a number. In this way it will be always a number
You need to check:
if Number(control.value) == NaN
// returns true if control.value is string
// else returns parsed number
First of all, the problem comes from the fact that JavaScript returns the type of NaN to be number. So maybe add additional check if the input is also not equal to NaN.
If the user changes the value in the input, the value becomes a string like "123".
This is a string but (in your case) it should be valid. So you have to check if this is parsable.
Better: you can set the input type from text to number
<input type="number" ...
Then it's always a number.
in addition: you can set the built-in validators min an max: https://angular.io/api/forms/Validators
Drawback is that you cannot use type="number" you need to use type="text" on the input but. But here is my solution as ValidatorFn:
function notANumber(): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} | null => {
const value = control.value
let nV = value
if (typeof value == 'string') {
nV = value.replace(',', '.')
}
return (Number.isNaN(Number(nV)) && !control.pristine) ? {notANumber: true} : null;
};
}

Check if an input string is a positive int/float number

On my webpage there is an input box that should only allow user to enter a positive int/float number (i.e. 1234, 123.4, 12.34, 1.234 should all be allowed).
To make sure the value is valid, I have a function to validate the value before sending it to the server:
function isPositiveFloat(s){
return String(Number(s)) === s && Math.floor(Number(s)) > 0;
}
The function works great expect for one scenario: isPositiveFloat(1.0) will return false, as it turns out Number(1.0) will convert it to 1, therefore made the validation failed.
Any suggestions on how should I resolve this issue? Is using regex the only way to go?
Thanks in advance for any help!
You just need to use !isNaN(s)along with Number(s)>0:
function isPositiveFloat(s) {
return !isNaN(s) && Number(s) > 0;
}
Demo:
function isPositiveFloat(s) {
return !isNaN(s) && Number(s) > 0;
}
<input type="text" onchange="console.log(isPositiveFloat(this.value))" />
You can check on the MDN reference of isNaN() examples that:
isNaN('37.37'); // false: "37.37" is converted to the number 37.37 which is not NaN
So as you can see it will be working in your case with float numbers.

Javascript: Ensure Input is Numbers Only

I have a unit conversion script; my HTML contains radio buttons (to pick the units), an input field, an output field and a button.
Here's a sample of my Javascript file:
[...]
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
document.getElementById("answer").innerHTML = convertObj.converted(initial);
});
[...]
});
function ConvertClass(){}
ConvertClass.prototype.converted = function(initialAmount){
if(document.getElementById("kilograms").checked) {
this.calculation = this.multiply(initialAmount, 2.2046);
} else if(document.getElementById("pounds").checked) {
this.calculation = this.divide(initialAmount, 2.2046);
}
return this.calculation.toFixed(2);
}
[...]
var convertObj = new ConvertClass();
I would like to add something that ensures a) an empty input field isn't considered a "0", and b) something other than a number doesn't display "NaN" as the answer. In both cases, I'd simply like my output to return nothing (blank). I don't want it to do nothing, in case the user submits a blank field or an invalid value after a correct number submission (which I think would result in the previous answer still being displayed.)
How do I write that? I'm assuming I should use conditions, but I don't know which ones. I did a bit of research and apparently using isNaN() isn't entirely accurate, at least not in this context.
Where do I put the code, in the function triggered by the page load or the one triggered by the button?
I'm still learning so, if possible, I'd really appreciate explanations along with the edited code. Thank you!
Inside ConvertClass.prototype.converted at the beginning of the function, add:
// this coerces it to a number instead of a string
// or NaN if it can't convert to a number
initialAmount = initialAmount.length > 0 ? +initialAmount : 0/0;
// if not a number, return empty string
if (isNaN(initialAmount)) {
return "";
}
If the input is an empty string 0/0 evaluates to NaN.
Add the following function to check whether a value in Integer.
function isInt(value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
}
Change your load function like this:
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
if(isInt(initial)){
document.getElementById("answer").innerHTML = convertObj.converted(initial);
}else{
document.getElementById("answer").innerHTML = '';
}
});
This will make sure that when a valid integer is supplied then only it will convert otherwise answer remain empty.
For further reading on how to check integer check this:
How to check if a variable is an integer in JavaScript?
Edit: setting answer to empty string when number not integer.

NaN comparison returns true?

The last days I read how NaN always compares false even with itself and how to compare stuff when NaN may occur, and now I made a JS that compares two NaN true. WTF? Or did I compare 'NaN' strings?
http://www.bksys.at/bernhard/JS-NaN-compare-true.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>radioactivity calculator</title>
</head>
<body>
<form name="form1">
a: <input type="text" name="a"><br>
b: <input type="text" name="b"><br>
x: <input type="text" name="x"><br>
</form>
<script type="text/javascript">
document.form1.a.value=Math.sqrt(-1);
document.form1.b.value=(1/0)/(1/0);
document.form1.x.value=(document.form1.a.value==document.form1.b.value);
</script>
</body>
</html>
You are indeed comparing the string "NaN" against another string "NaN", which equates to true. The value held in text input elements is always pulled as a String type.
A simple way to resolve this is to prefix your values with the Unary Plus (+) operator to convert them to integer values (you can drop those brackets, too):
document.form1.x.value = +document.form1.a.value == +document.form1.b.value;
Example
document.form1.a.value = Math.sqrt(-1);
document.form1.b.value = (1/0) / (1/0);
document.form1.x.value = +document.form1.a.value == +document.form1.b.value;
<form name="form1">
a: <input type="text" name="a" size="20" value="a"><br>
b: <input type="text" name="b" size="20" value="b"><br>
x: <input type="text" name="x" size="20" value="x"><br>
</form>
Note: As RobG pointed out in his comment below it's important to note here that converting the string value "NaN" to an integer with the Unary Plus operator converts it directly to NaN because the string cannot be replicated as a numeric value. The same would happen if both of your input elements contained the value "Foo" - or even contained two completely different non-numeric string values. Whilst this solution does work, it may yield undesired results if you are to extend this code to handle non-numeric values as well.
This is a JavaScript gotcha ;)
The proper way to compare NaN is to use the isNaN method.
var a = 'a' + 5; //NaN
if (isNaN(a)) {
//do something
}
NaN is a special value in JavaScript. It doesn't even equal itself (also a quick way to test):
var a = parseInt('seven');
if (a == a) {
alert("a == a");
} else {
alert("a != a"); // This will happen
}
if (a == 'NaN') {
// Won't happen
} else {
alert("NaN is not equal to the string 'NaN'"); // Here
}
http://jsfiddle.net/u951v90o/

Differentiate between NaN input and empty input with an Input of type="number"

I want to use a form input with type="number" and only allow numbers to be entered.
<input type="number" class="form-control fc-input"/>
I don't have a submit button, instead the value is checked after the input loses focus. However when you use type="number" and a non-number is entered, both the valueAsNumber and the value attributes of the input will be useless (NaN respectively ""). The problem with this is that I want to differentiate between the user entering an empty string (""), and the user entering a non-number value (e.g. 123abc). When the input is empty I want to execute function a, and if it's just a non-number I want to execute function b (otherwise do c).
Is there a good way to differentiate between NaN input and empty ("") input like this?
The problem is input type of number does a lot of stuff under the covers and the specification for it does not expose the actual invalid value to you. So an empty input and an invalid string look the same. So you need to do some investigation work using validity
var result = document.getElementById("result");
document.getElementById("num").addEventListener("keyup", function() {
var isValid = this.validity.valid;
var len = this.value.length;
if (isValid && !len) {
result.innerHTML = "No value";
} else if (!isValid) {
result.innerHTML = "Invalid number";
} else {
result.innerHTML = "Valid number: " + this.valueAsNumber;
}
});
<input type="number" id="num" />
<span id="result"></span>
Problem with the code above is if you make it required, the empty check will fail. If it is required the if check would need to be
if (!isValid && this.validity.valueMissing) {

Categories

Resources