UNPKG

1.84 kBJavaScriptView Raw
1var titleCase = require('titlecase');
2var upperCaseFirst = require('upper-case-first');
3
4var sanitizer = module.exports = {};
5
6
7/*
8 * options = { radix = 10 }
9 */
10sanitizer.toInt = function(ctx, options, value) {
11 if (value === null) return value;
12
13 options.radix = options.radix || 10;
14 return parseInt(value, options.radix);
15};
16
17
18/*
19 * options = { precision }
20 */
21sanitizer.toFloat = function(ctx, options, value) {
22 if (value === null) return value;
23
24 value = parseFloat(value);
25 if (typeof options.precision != 'undefined') {
26 value = value.toFixed(options.precision);
27 value = parseFloat(value);
28 }
29 return value;
30};
31
32
33sanitizer.toDate = function(ctx, options, value) {
34 if (value === null) return value;
35 return new Date(value);
36};
37
38
39/*
40 * options = { chars }
41 */
42sanitizer.trim = function(ctx, options, value) {
43 if (value === null) return value;
44
45 value += '';
46
47 options.chars = options.chars || '\\r\\n\\t\\s';
48
49 return value.replace(new RegExp('^[' + options.chars + ']+|[' + options.chars + ']+$', 'g'), '');
50};
51
52sanitizer.string = function(ctx, options, value) {
53 if (value === null) return value;
54
55 return String(value);
56};
57
58sanitizer.lowerCase = function(ctx, options, value) {
59 if (value === null) return value;
60
61 return String(value).toLowerCase();
62};
63
64sanitizer.titleCase = function(ctx, options, value) {
65 if (value === null) return value;
66
67 return titleCase(value);
68};
69
70sanitizer.upperCaseFirst = function(ctx, options, value) {
71 if (value === null) return value;
72
73 return upperCaseFirst(value);
74};
75
76sanitizer.upperCase = function(ctx, options, value) {
77 if (value === null) return value;
78
79 return String(value).toUpperCase();
80};
81
82sanitizer.toBool = function(ctx, options, value) {
83 if (value === null) return value;
84
85 const strVal = String(value).toLowerCase();
86 return strVal === 'true';
87};