Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - What is the opposite of isNaN?

I am very new to JavaScript, and trying to run a simple script which gives my field a red border if it is incorrectly completed (i.e. if the entry is not a number), but then turns the border colour green if the field is then correctly completed, but the form cannot be submitted because a different field has been filled out incorrectly.

So far i have managed to do this for a text field by using this:

function validateForm()
{
var x=document.forms["myForm"]["FN"].value;
if (x==null || x=="")
  {
  alert("First name must be completed");
  document.forms["myForm"]["FN"].style.border="1px solid red";
  return false;
  }
  else (x!==null || x!=="")
  {
  document.forms["myForm"]["FN"].style.border="1px solid green";
  }

but I am now trying to do the same thing but limit the field to only accept numbers. What I have so far is this:

var x=document.forms["myForm"]["mobile"].value;
if (isNaN(x) || x==null || x=="")
  {
  alert("Contact number must be completed with numbers only");
  document.forms["myForm"]["mobile"].style.border="1px solid red";
  return false;
  }
  else (x!==null || x!=="" || // need to write here is not isNaN !isNaN//)
  {
  document.forms["myForm"]["SN"].style.border="1px solid green";
  }

This restricts the fie;ld to only allowing numbers, but once the form box border turns red, it will not turn to green once the validation has been met.

Any help/tips on how to write is not isNaN, or any work arounds would be appreciated.

Please try to keep as simple as poss, as am a complete beginner with web design & JavaScript.

Thanks!

like image 528
cj69 Avatar asked Jan 11 '14 22:01

cj69


People also ask

What does isNaN () in JavaScript do?

isNaN() returns true if a number is Not-a-Number. In other words: isNaN() converts the value to a number before testing it.

What is NaN in JavaScript?

In JavaScript, NaN is short for "Not-a-Number". In JavaScript, NaN is a number that is not a legal number. The Global NaN property is the same as the Number.

What is the difference between NaN and isNaN in JavaScript?

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 .

What is the opposite of isNaN?

The opposite of isNaN is ! isNaN , reads like: "isn't not a number" therefore, it's a number.


1 Answers

The literal opposite of isNaN(num) is !isNaN(num). However, this won't always verify that something is numeric. To check if something is numeric, use jQuery's $.isNumeric(num), or this

function isNumeric(num) {
  return !isNaN(parseFloat(num)) && isFinite(num);
}
like image 119
scrblnrd3 Avatar answered Oct 20 '22 00:10

scrblnrd3