-3

This is my code

else if(form.txtPrice.IsNumber){
    alert("Price must be number") form.txtPrice.focus();
    return false;

I can not check validation must be number in Javascript, everybody help me please, thank you so much!

Marty
  • 146
  • 1
  • 13
  • `Number(form.txtPrice.value) === NaN` – Keith Mar 29 '19 at 12:19
  • 3
    Please [format](https://stackoverflow.com/help/formatting) your question, and have a look at [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Andreas Mar 29 '19 at 12:20
  • @Keith you shouldnt provide answers in comments, it circumvents the voting process which helps determine good/bad/safe/unsafe answers – Marie Mar 29 '19 at 14:05

2 Answers2

0

Use isNaN(value).

This returns true if the value is not a number. If the value is a number, will return false.

lok30
  • 114
  • 9
0

Using only isNaN is risky, it has some big inconvenient; These strings will be considered valid numbers:

  • 'Infinity'
  • '1e355'
  • '0xf'
  • empty string

you could do more:

function isNumber(input) {
  return typeof input === "number" && !isNaN(input);
}

note that you have to parse if before if you have a string (parseInt/parseFloat)

Apolo
  • 3,844
  • 1
  • 21
  • 51
  • 1
    To be fair, they are valid numbers just in different and unexpected formats – Marie Mar 29 '19 at 14:03
  • `typeof Infinity , 1e355 , 0xf` are all `number` There is `Number.isFinite` is you want to prevent those. – Keith Mar 29 '19 at 14:25
  • I'm talking about user input strings, for eg. `input = "Infinity";` which is valid number according to `isNaN`. This should disable implicit parsing. Furthermore, `parseInt('Infinity')` returns NaN, which is good IMO – Apolo Apr 01 '19 at 12:33
  • I still agree they are valid numbers, just not the format you want your users to send – Apolo Apr 01 '19 at 12:34