Skip to content

Commit dead663

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

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/defaultConverters.ts

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

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

src/options.ts

Lines changed: 7 additions & 0 deletions
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)