forked from typestack/class-validator
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add
@IsTimeZone
validator (typestack#1796)
Co-authored-by: chandra shekhar <shekharneupane23@gmail.com>
- Loading branch information
1 parent
c913e3c
commit 6fa5680
Showing
4 changed files
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import { ValidationOptions } from '../ValidationOptions'; | ||
import { buildMessage, ValidateBy } from '../common/ValidateBy'; | ||
|
||
export const IS_TIMEZONE = 'isTimeZone'; | ||
|
||
/** | ||
* Checks if the string represents a valid IANA timezone | ||
* If the given value is not a valid IANA timezone, then it returns false. | ||
*/ | ||
export function isTimeZone(value: unknown): boolean { | ||
try { | ||
if (typeof value !== 'string') { | ||
return false; | ||
} | ||
|
||
/** Specifying an invalid time-zone will raise a `RangeError: Invalid time zone specified` error. */ | ||
Intl.DateTimeFormat(undefined, { timeZone: value }); | ||
|
||
return true; | ||
} catch (exception) { | ||
return false; | ||
} | ||
} | ||
|
||
/** | ||
* Checks if the string represents a valid IANA timezone | ||
* If the given value is not a valid IANA timezone, then it returns false. | ||
*/ | ||
export function IsTimeZone(validationOptions?: ValidationOptions): PropertyDecorator { | ||
return ValidateBy( | ||
{ | ||
name: IS_TIMEZONE, | ||
validator: { | ||
validate: (value, args): boolean => isTimeZone(value), | ||
defaultMessage: buildMessage( | ||
eachPrefix => eachPrefix + '$property must be a valid IANA time-zone', | ||
validationOptions | ||
), | ||
}, | ||
}, | ||
validationOptions | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters