-
Notifications
You must be signed in to change notification settings - Fork 777
/
IsNumber.ts
62 lines (54 loc) · 1.5 KB
/
IsNumber.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { ValidationOptions } from '../ValidationOptions';
import { buildMessage, ValidateBy } from '../common/ValidateBy';
export const IS_NUMBER = 'isNumber';
/**
* Options to be passed to IsNumber decorator.
*/
export interface IsNumberOptions {
allowNaN?: boolean;
allowInfinity?: boolean;
maxDecimalPlaces?: number;
}
/**
* Checks if a given value is a number.
*/
export function isNumber(value: unknown, options: IsNumberOptions = {}): boolean {
if (typeof value !== 'number') {
return false;
}
if (value === Infinity || value === -Infinity) {
return options.allowInfinity;
}
if (Number.isNaN(value)) {
return options.allowNaN;
}
if (options.maxDecimalPlaces !== undefined) {
let decimalPlaces = 0;
if (value % 1 !== 0) {
decimalPlaces = value.toString().split('.')[1].length;
}
if (decimalPlaces > options.maxDecimalPlaces) {
return false;
}
}
return Number.isFinite(value);
}
/**
* Checks if a value is a number.
*/
export function IsNumber(options: IsNumberOptions = {}, validationOptions?: ValidationOptions): PropertyDecorator {
return ValidateBy(
{
name: IS_NUMBER,
constraints: [options],
validator: {
validate: (value, args): boolean => isNumber(value, args.constraints[0]),
defaultMessage: buildMessage(
eachPrefix => eachPrefix + '$property must be a number conforming to the specified constraints',
validationOptions
),
},
},
validationOptions
);
}