diff --git a/lib/types/string.js b/lib/types/string.js index e78439b2996ca59119cd550ed56c7ab8bc0ac79e..c79b82b4c93ed52b982893f74adb56557945b566 100644 Binary files a/lib/types/string.js and b/lib/types/string.js differ diff --git a/spec/schema/core/issues/issue-193.json b/spec/schema/core/issues/issue-193.json new file mode 100644 index 0000000000000000000000000000000000000000..5d495d9f2a12623e7ded082d88130232aeaa731b --- /dev/null +++ b/spec/schema/core/issues/issue-193.json @@ -0,0 +1,25 @@ +[ + { + "description": "pattern and min/max length constraints", + "tests": [ + { + "description": "should support minLength", + "schema": { + "type": "string", + "pattern": ".+", + "minLength": 21 + }, + "valid": true + }, + { + "description": "should support maxLength", + "schema": { + "type": "string", + "pattern": ".+", + "maxLength": 2 + }, + "valid": true + } + ] + } +] diff --git a/ts/types/string.ts b/ts/types/string.ts index 926a0bae9eac2ff36ee70587214745281c66081e..39d5f7ec3fc4f368364b88298770ee37c2910856 100644 --- a/ts/types/string.ts +++ b/ts/types/string.ts @@ -29,28 +29,40 @@ function generateFormat(value: IStringSchema): string { } var stringType: FTypeGenerator = function stringType(value: IStringSchema): string { + var output: string; + + var minLength = value.minLength; + var maxLength = value.maxLength; + + if (option('maxLength')) { + // Don't allow user to set max length above our maximum + if (maxLength && maxLength > option('maxLength')) { + maxLength = option('maxLength'); + } + + // Don't allow user to set min length above our maximum + if (minLength && minLength > option('maxLength')) { + minLength = option('maxLength'); + } + } + if (value.format) { - return generateFormat(value); + output = generateFormat(value); } else if (value.pattern) { - return randexp(value.pattern); + output = randexp(value.pattern); } else { - var minLength = value.minLength; - var maxLength = value.maxLength; - - if (option('maxLength')) { - // Don't allow user to set max length above our maximum - if (maxLength && maxLength > option('maxLength')) { - maxLength = option('maxLength'); - } - - // Don't allow user to set min length above our maximum - if (minLength && minLength > option('maxLength')) { - minLength = option('maxLength'); - } - } + output = thunk(minLength, maxLength); + } - return thunk(minLength, maxLength); + while (output.length < minLength) { + output += Math.random() > 0.7 ? thunk() : randexp('.+'); } + + if (output.length > maxLength) { + output = output.substr(0, maxLength); + } + + return output; }; export = stringType;