Javascript: Ensure Input is Numbers Only - javascript

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.

Related

Finding variable types from a string

Pardon if this question has already been answered however I'm struggling to find the any answers to it.
I'm looking to see if I can convert variable types to a string in the code below.
input = prompt('Type something please', 'your input here')
alert(input + ' is a ' + typeof input)
i.e. if the user were to type 1 typeof would return number, or if the user were to enter true it would return a boolean
You can run the input through a series of parseInt, parseFloat and
parseBool
functions.
Whenever you get a valid result, return it.
Something similar to:
if (parseInt(input) != NaN) {
return "int"
}
if (parseFloat(input) != NaN) {
return "float"
}
Generally, all inputs per your example will return a string careless of what they entered or intended to enter. We could however build a few logics to check if what they entered is; Strings (Alphabets only) or an integer (numbers only) or any other ones per a few other logics you could base your checks on.
One of the quickest ways to check if an input contains a number or not;
isNaN(input) // this returns true if the variable does NOT contain a valid number
eg.
isNaN(123) // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
you could try regex (which is not always ideal but works)
var input = "123";
if(num.match(/^-{0,1}\d+$/)){
//return true if positive or negative
}else if(num.match(/^\d+\.\d+$/)){
//return true if float
}else{
// return false neither worked
}
You could also use the (typeof input) but this will be more convenient if your user is going to enter an expected set of entries
var input = true;
alert(typeof input);
// This eg will return bolean
Let me know if this helps.

convert string to boolean and compare with if condition in js

I have an attribute where I have got condition .I took that condition from tag's attribute now I want place that condition in if block and get result.
my code:-
<div myCondition="1 == 2" id="hey"></a>
<script>
var a = document.getElementById('hey');
var x = a.getAttribute('myCondition');
if(x){
console.log('accepted')
}else{
console.log('not accepted')
}
</script>
above program should return not accepted
value of myCondition attribute can be very complex for example:-
'hello' == 'hello'
5>1 etc
I guess what you need is the eval function. As it says in the provided link:
The eval() function evaluates JavaScript code represented as a string.
So, you can change your code like this:
if( eval(x) ){
console.log('accepted')
}else{
console.log('not accepted')
}
P.S: That being said, I don't think doing it like this really safe.

how to check input value has only numbers in angular?

I want to compare a value of a field centerCode which is entered by a user into an input field. Then I want to check if it is a number and show the appropriate alert accordingly. I am not able to compare the value or variable number with the variable code .
var numbers =/^[0-9]+$/;
var code = $scope.Nuser.centerCode;
alert(code);
if(code.val(numbers))
{
alert(code.val(numbers));
}
else
{
alert("enter numbers only");
}
You're along the right lines. Numbers needs to be a Regex though, and you need to use the test function to check the input against it. The test function will return true if the string is all numbers, or false if there is anything else in it.
var numbers = new RegExp(/^[0-9]+$/);
var code = $scope.Nuser.centerCode;
if(numbers.test(code))
{
alert('code is numbers');
}
else
{
alert("enter numbers only");
}
I would suggest you to use ng-pattern instead . Something like following :
<input type="text" ng-pattern="/^[0-9]{1,7}$/" ng-model="inputNumber"/>
It will only allow the user to enter the number.
You can use angular.isNumber to check if the entered value is a number or not. Try something like the following :
if(angular.isNumber($scope.Nuser.centerCode)){
alert('Center Code is a number');
}else {
alert('Center Code is not a number');
}
Hope this will do the trick.
You can simply convert string to number and test is it's NaN (Not a Number)
isNaN(+$scope.Nuser.centerCode)
if it's false it means your centerCode contain only numbers
try this hope this is what you are looking for
if(angular.isNumber(value))
{
//your code here
}

Javascript Replace - Regular Expression

I need to replace a code example: OD3 - The first must always be alpha character, 2nd alphanumeric and the last must always be numeric. What's the regular expression to check and replace the first and regulate the rest to enter correctly? A user could enter in the number 0 instead of the letter O, so I want to correct it immediately...
this is what I have so far: onkeyup="this.value=this.value.replace(/[^a-zA-z]/g,'')
First, I'd suggest just indicating the error to a user instead of replacing the values. Something like
oninput="if (! /^[a-z][a-z0-9]\d$/i.test(this.value) ) displayMessage('incorrect code');"
If you definitely have to replace the value on the fly, you could do somthing like that:
oninput='validateValue()';
...
function validateValue() {
var val = this.value;
if (! /[a-z]/i.test(val[0]) this.value = '';
else if (! /[a-z0-9]/i.test(val[1]) this.value = val.slice(0,1);
else if (! /\d/.test(val[2]) this.value = val.slice(0,2);
}
Better have like this.
onkeyup="testRegex(this.value)";
It is not .replace() it is .test()
function testRegex(value) {
if(value.test(/[^a-zA-z]/g)) {
alert("Please enter correct value");
return false;
}
}

Javascript regex to validate GPS coordinates

I have a form where a user inserts the GPS coordinates of a location to a corresponding photo. Its easy enough to filter out invalid numbers, since I just have to test for a range of (-90, 90), (-180, 180) for lat/long coordinates.
However, this also means that regular text is valid input.
I've tried changing the test pattern to
var pattern= "^[a-zA-Z]"
and is used in the function to detect alphabetical characters
$(".lat").keyup(function(){
var thisID= this.id;
var num = thisID.substring(3, thisID.length);
var thisVal = $(this).val();
//if invalid input, show error message and hide save button
if (pattern.test(thisVal)){
$("#latError"+num).fadeIn(250);
$("#save"+num).fadeOut(100)
}
else { //otherwise, hide error message and show save
$("#save"+num).fadeIn(250);
$("#latError"+num).fadeOut(100);
}
});
However, this doesn't work as Firebug complains that pattern.test is not a function What would solve this issue?
This is what i use in my project:
const regexLat = /^(-?[1-8]?\d(?:\.\d{1,18})?|90(?:\.0{1,18})?)$/;
const regexLon = /^(-?(?:1[0-7]|[1-9])?\d(?:\.\d{1,18})?|180(?:\.0{1,18})?)$/;
function check_lat_lon(lat, lon) {
let validLat = regexLat.test(lat);
let validLon = regexLon.test(lon);
return validLat && validLon;
}
check_lat_lon(-34.11242, -58.11547) Will return TRUE if valid, else FALSE
I hope this will be usefull to you!
Do you need to use regex? Consider the following:
var val = parseFloat(lat);
if (!isNaN(val) && val <= 90 && val >= -90)
return true;
else
return false;
How about the pattern -?[0-9]{1,3}[.][0-9]+ then you parseInt and check the range as you said before.
test() is a method of the RegExp object - you're running it on a string, so will fail.
Enclose your pattern in a RegExp literal (/pattern/), so
var pattern= /^[a-zA-Z]/
That will get rid of the errors you're getting, but you have a separate issue with regards to a) whether your pattern is correct for what you want it to do; b) whether you need REGEX at all.
REGEX acts on strings - it cannot be used to determine whether a number is within a given range (unless that range is 0-10 inclusive).
#flem's answer shows the best way to approach what you're doing - no REGEX needed. The call to parseInt() will catch non-numeric characters since it will return NaN if the value contains any.
#paul flemming gave a great answer, this answer extends his and includes longitude and uses typescript.
I would suggest this in place of regex for speed and simplicity.
Since, parseFloat takes a string and returns a number isNaN check isn't needed. This function allows a string or a number and converts it to string for parseFloat and will then do the simple threshold tests against +-90 & +-180.
function isValidLatAndLong(lat: number |string, lon:number|string){
const num1 = "" +lat; //convert toString
const num2 = "" +lon;
if (parseFloat(num1) <= 90 && parseFloat(num1) >= -90 && parseFloat(num2) <= 180 && parseFloat(num2) >= -180){
return true;
}
else{
return false;
}
}

Categories

Resources