Skip to content

Commit 05f3ecf

Browse files
committed
add string convert sanitizer
1 parent 8d803f6 commit 05f3ecf

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

lib/rules/string.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,16 @@ const ALPHADASH_PATTERN = /^[a-zA-Z0-9_-]+$/;
1010
module.exports = function checkString({ schema, messages }, path, context) {
1111
const src = [];
1212
let sanitized = false;
13+
14+
if (schema.convert === true) {
15+
sanitized = true;
16+
src.push(`
17+
if (typeof value !== "string") {
18+
value = String(value);
19+
}
20+
`);
21+
}
22+
1323
src.push(`
1424
if (typeof value !== "string") {
1525
${this.makeError({ type: "string", actual: "value", messages })}

test/rules/string.spec.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,8 +134,50 @@ describe("Test rule: string", () => {
134134

135135
});
136136

137+
it("should convert & check values", () => {
138+
const check = v.compile({ $$root: true, type: "string", convert: true });
139+
expect(check("")).toEqual(true);
140+
expect(check([])).toEqual(true);
141+
expect(check(false)).toEqual(true);
142+
expect(check(true)).toEqual(true);
143+
144+
expect(check(100)).toEqual(true);
145+
expect(check(34.76)).toEqual(true);
146+
expect(check(-45)).toEqual(true);
147+
expect(check(new Date())).toEqual(true);
148+
});
149+
137150
describe("Test sanitization", () => {
138151

152+
it("should convert & check values", () => {
153+
const check = v.compile({ age: { type: "string", convert: true } });
154+
155+
let obj = { age: 100 };
156+
expect(check(obj)).toEqual(true);
157+
expect(obj).toEqual({ age: "100" });
158+
159+
obj = { age: 34.76 };
160+
expect(check(obj)).toEqual(true);
161+
expect(obj).toEqual({ age: "34.76" });
162+
163+
obj = { age: true };
164+
expect(check(obj)).toEqual(true);
165+
expect(obj).toEqual({ age: "true" });
166+
167+
obj = { age: false };
168+
expect(check(obj)).toEqual(true);
169+
expect(obj).toEqual({ age: "false" });
170+
171+
obj = { age: [1,2,3] };
172+
expect(check(obj)).toEqual(true);
173+
expect(obj).toEqual({ age: "1,2,3" });
174+
175+
const d = new Date();
176+
obj = { age: d };
177+
expect(check(obj)).toEqual(true);
178+
expect(obj).toEqual({ age: d.toString() });
179+
});
180+
139181
it("should trim", () => {
140182
const check = v.compile({ username: { type: "string", trim: true, max: 6 } });
141183

0 commit comments

Comments
 (0)