javascript/jQuery: validating numbers coming from .val() - javascript

I'm validating my form, just checking if in the fields where a number should be the user has entered an string. But as I'm getting all the field values like this:
var number= $("#number").val();
All my variables are strings.
alert(typeof number);
shows "string" with all numeric fields values.
Any ideas on how can I validate integers??
Thanks a lot

You can use
jQuery.isNumeric( value )
method for this purpose. As a result you don't need any extra parsing effort.
DEMO
Read more about $.isNumeric()
For manual parse(if you don't use above)
var number = parseInt($("#number").val(), 10);
and for check
if(isNaN(number)) {
// do something
} else {
// do something else
}

isNaN(parseInt($("#number").val())); should do the trick! If you want to work with the number at all, this might be an easier way:
var value = parseInt($("#number").val());
if (isNaN(value)) {
console.log("invalid input");
} else {
console.log("user entered: " + value);
}

Related

javascript isNaN() function not working?

I have a function to test if a prompt input is a number, like so:
function myFunction()
{
var person = prompt("Please enter your name", "");
if (person != null)
{
if(isNaN(person))
{
document.write("hello " + person + "<br><br>");
}
else
document.write("You gave me a number");
}
else
{
document.write("You didn't answer.<br><br>");
}
}
but every time I enter a number it keeps outputting hello + the number. I've been googling this function for quite some time and it doesn't make sense to me, it seems like it should work. Why is person returning true?
NaN is a special value in Javascript. What isNaN does is check to see if the value passed is equal* to this special value. If you want to check if something is, say, not a stream of numbers, you can use a regular expression:
if (!/^\d+(\.\d+)?/.exec(person)) {
Or parse the value as a number and see if it converts back to the same string:
var n = parseFloat(person);
if (n.toString() !== person) {
*There's a reason that we don't use === but it's outside the scope of this answer.
The isNaN function checks if a value is NaN. NaN is a value that occurs when making operations that require numbers with non-numbers. Please see the documentation.
However the function does not check if the value is of type number. Too check if a value is of type number use the typeof operator
typeof person === 'number'
Your code is the correct way of using the isNaN method. However for anyone else reading this post I have seen a strange anomaly where the documented usage of IsNaN hasn't worked properly and I got around the problem by combining the parseInt method with the IsNaN method. According to the W3c web site (https://www.w3schools.com/jsref/jsref_isnan.asp) the IsNan('123') should return false and IsNan('g12') should return true, but I've seen scenarios where this isn't the case.
If you're having trouble getting the documented methods to work try this code below:
var unitsToAdd = parseInt($('#unitsToAdd').val());
if(isNaN(unitsToAdd)) {
alert('not a number');
$('#unitsToAdd').val('1');
returnVal = false;
}
Alternatively you can try this method which is well tested.
function isNumber(searchValue) {
var found = searchValue.search(/^(\d*\.?\d*)$/);
//Change to ^(\d*\.?\d+)$ if you don't want the number to end with a . such as 2.
//Currently validates .2, 0.2, 2.0 and 2.
if(found > -1) {
return true;
}
else {
return false;
}
}
Hope this helps.

How can I modify JavaScript to not allow letters in a field?

I am using isNAN at the moment but I can't seem to get it to work.
if (isNAN(getElementById("Bob")))
You can use something along the lines of this function to basically check if inp has letters in it.
function checkLetter(inp)
{
var letters = /^[A-Za-z]+$/;
if(inp.value.match(letters)){
//Letters
}
else {
//no letter
}
}
Try this:
if (isNaN(document.getElementById("Bob").value))
You are not using proper syntax in your code to get value. Also make sure you are using isNaN() and not isNAN().
If you want to check empty values also:
var myVar = document.getElementById("Bob").value;
if(!myVar || isNaN(myVar))
alert("Not a number!");
else
alert("Is a number!");
you have to check the value, not the object
if (isNAN(getElementById("Bob").val()) ){
//
}
EDIT so if you just want lock the field contains numeric values you can do this in html5 :
<input type="number" />
Here is a way to check if only number exists not letters
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
So the use will be like
nn=document.getElementById("Bob").value;
ans=isNumber(nn);
if(ans)
{
//only numbers
}
This ans was found from here
Validate numbers in JavaScript - IsNumeric()

Javascript if else condition run time failure

I have started javascript today. Trying with the very basic and got stuck with If Else loop.
var input = prompt("type your name"); //variable stores the value user inputs
var outout = tostring(input); // the input value is changed to string datatype and stored in var output
alert(output);//supposed to display the value which it doesn't
if(output == "Tiger")
{alert("It is dangerous");
}
Else
{alert("all is well");
}//I only get a blank page
If I omit the line var output = tostring(input) and try to display the alert box with input value I get the alert box. But after that I only get a blank page. The If Else loop doesn't work at all. I am using notepad++. Also checked in Dreamweaver. There is no compile error. What am I doing wrong?
Sorry for such a basic question and thanks for replying.
Regards,
TD
Your line
tostring(input);
Should be
toString(input);
The toString() method has a capital S
Also, your output variable is called "outout". Don't know if that's a typo...
Not only that, your Else should also have a small e. All JavaScript keywords are case sensitive.
You do not have to convert the result of a prompt to a string, it is a string already. And it actually would be
input.toString()
And Else is lowercase, the correct would be else.
So you can use like this
var input = prompt("Type your name");
if (input == "Tiger")
{
alert("Wow, you are a Tiger!");
}
else
{
alert("Hi " + input);
}
Notice that if you type tiger (lowercase) you will end up on the else. If you want to compare a string case insensitive you can do this:
if (input.toLowerCase() == "tiger")
Then even tIgEr will work.
Your code has the following problems:
var input = prompt("type your name");
var outout = tostring(input);
// Typo: outout should be output
// tostring() is not a function as JavaScript is case-sensitive
// I think you want toString(), however in this context
// it is the same as calling window.toString() which is going to
// return an object of some sort. I think you mean to call
// input.toString() which, if input were not already a string
// (and it is) would return a string representation of input.
alert(output);
// displays window.toString() as expected.
if(output == "Tiger")
{alert("It is dangerous");
}
Else // JavaScript is case-sensitive: you need to use "else" not "Else"
{alert("all is well");
}//I only get a blank page
I suspect what you want is this:
var input = prompt("type your name");
alert(input);
if (input === "Tiger") {
alert("It is dangerous");
} else {
alert("all is well");
}

Am I using the isNAN function in JavasScript correctly here?

I've got a form where the user inputs 3 values, which are then calculated. The outputs are displayed again within the form in some "readonly" output boxes. For each input, I want to validate if they are a number, if not, instead of the form showing "NaN" I want to display an error saying, "Please enter a number" (or something like that). Below is the code I am using, which is executed "onkeyup":
function checkforNumber()
{
if (isNaN(sInput || dInput || pInput) == true) {
alert("You entered an invalid character. Please reset the form.");
}
else {
return(false);
}
}
Am I using this function incorrectly? Is there something wrong with the syntax?
Thanks
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
alert("You entered an invalid character. Please reset the form.");
}
also make sure that those 3 variables sInput, dInput and pInput are not strings but were obtained by using parseFloat or parseInt methods.
var sInput = parseFloat(document.getElementById('sinput').value);
var dInput = parseFloat(document.getElementById('dinput').value);
var pInput = parseFloat(document.getElementById('pinput').value);
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput))
This is what I think you intended. You need to pass each value you want to test in to the isNaN function one at a time. Also note that you don't need the == true part, because isNaN returns true or false so the condition will evaluate to the return value.

Error with validation process by input data

Goal:
I dont wanna retrieving any data if the input data contain any alphabet.
Problem:
If I have input data "23w" in variable ddd, the process on convertion is accceptable to be "23" in the variable currentvalue.
I don't want it to be converted into number if the input data contain
any alphabet.
The sourcecode is writtin in jQuery and if possible it would be great to retreive the new solution in jQuery.
// Fullmetalboy
var ddd = $('#field_hourInput').val();
var currentValue = parseInt(ddd);
// Validating message
if(currentValue <= 0)
{
alert("Value must be positiv");
nonError = false;
}
else if( (isNaN(currentValue)) && (ddd != "") )
{
alert("value must contain numbers");
nonError = false;
}
else if( (isNaN(currentValue)) && (ddd == "") )
{
alert("value must contain value in the textbox");
nonError = false;
}
parseint() will return a number if the string begins with one, even if there is non-numbers following it. For example: http://jsfiddle.net/uQztw/
Probably better to use a regex. Something like
http://jsfiddle.net/uQztw/1/
You can use regex to validate that. Using regex with jquery. And using regex
[\d]
which will match any digit should do the trick.
Another way to convert string to int is Number(ddd), it does what you expect. But you could also check ddd through a regular expression, which feels better to me.
regexp-test: /^\d+$/.test(ddd)

Categories