Skip to content

Commit deade41

Browse files
committed
feat: @IsStrongPassword() converter
1 parent 4821a25 commit deade41

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/defaultConverters.ts

+41
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,47 @@ export const defaultConverters: ISchemaConverters = {
365365
type: 'array',
366366
uniqueItems: true,
367367
},
368+
[cv.IS_STRONG_PASSWORD]: (meta, options) => {
369+
const {
370+
minLength = 8,
371+
minLowercase = 1,
372+
minUppercase = 1,
373+
minNumbers = 1,
374+
minSymbols = 1,
375+
}: cv.IsStrongPasswordOptions = meta.constraints[0]
376+
377+
const requireChars = (chars: string, amount: number): string => {
378+
const charMatcher = chars === '*' ? '' : `*(?:[^${chars}]*[${chars}])`
379+
380+
return `(?=.${charMatcher}{${amount}})`
381+
}
382+
383+
const requirements = (
384+
[
385+
['*', minLength],
386+
['a-z', minLowercase],
387+
['A-Z', minUppercase],
388+
['0-9', minNumbers],
389+
[options.passwordSymbols, minSymbols],
390+
] as const
391+
)
392+
.map(([chars, amount]) => {
393+
if (!amount) {
394+
return
395+
}
396+
397+
return requireChars(chars, amount)
398+
})
399+
.filter(Boolean)
400+
.join('')
401+
402+
const pattern = `^${requirements}.*$`
403+
404+
return {
405+
type: 'string',
406+
pattern,
407+
}
408+
},
368409
}
369410

370411
function getPropType(target: object, property: string) {

src/options.ts

+7
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,18 @@ export interface IOptions extends ValidatorOptions {
4040
* Defaults to `name`, i.e., class name.
4141
*/
4242
schemaNameField: string
43+
44+
/**
45+
* Characters that are considered symbols n passwords.
46+
* Defaults to the symbol character set of `validator.js`.
47+
*/
48+
passwordSymbols: string
4349
}
4450

4551
export const defaultOptions: IOptions = {
4652
additionalConverters: {},
4753
classValidatorMetadataStorage: getMetadataStorage(),
4854
refPointerPrefix: '#/definitions/',
4955
schemaNameField: 'name',
56+
passwordSymbols: '-#!$@£%^&*()_+|~=`{}\\[\\]:";\'<>?,.\\/ ',
5057
}

0 commit comments

Comments
 (0)