Skip to content

Commit

Permalink
Tipify number validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Chalarangelo committed May 19, 2024
1 parent 5d9c484 commit 975c4dc
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 25 deletions.
2 changes: 2 additions & 0 deletions content/languages/javascript.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,8 @@ references:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
Number: >-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
Number(): >-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number
Number.EPSILON: >-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON
Number.MAX_SAFE_INTEGER: >-
Expand Down
3 changes: 3 additions & 0 deletions content/redirects.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2920,3 +2920,6 @@
- from: /js/s/count-substrings
to: /js/s/count-occurences
status: 301!
- from: /js/s/validate-number
to: /js/s/number-validation
status: 301!
26 changes: 26 additions & 0 deletions content/snippets/js/s/number-validation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
title: Validate a number in JavaScript
shortTitle: Validate number
type: tip
language: javascript
tags: [math]
cover: flower-portrait-9
excerpt: Check if a value can be safely converted to a number in JavaScript.
dateModified: 2024-05-17
---

Number validation is probably one of the hardest things to do even for intermediate developers. However, it's a necessary evil, especially when working with **user input**. It's even more so in JavaScript, due to the language's quirks and the fact that it's loosely typed.

While, a simple check that `parseFloat()` produces a sensible **numeric value** might seem enough, it's a little more involved than that. You also need to check for `NaN`, using `Number.isNaN()`, and for `Infinity`, using `Number.isFinite()`.

And, as if that wasn't already enough, you also need to check if the **coercion** of the value to a number is correct, using `Number()` and the loose equality operator (`==`). Putting everything together, you get a pretty robust number validation function.

```js
const validateNumber = n => {
const num = parseFloat(n);
return !Number.isNaN(num) && Number.isFinite(num) && Number(n) == n;
}

validateNumber('10'); // true
validateNumber('a'); // false
```
25 changes: 0 additions & 25 deletions content/snippets/js/s/validate-number.md

This file was deleted.

0 comments on commit 975c4dc

Please sign in to comment.