Commit c7a65d70 authored by Emmanuel Raviart's avatar Emmanuel Raviart
Browse files

New `validateKeyValueDictionary` validator.

parent 0ce9e16d
......@@ -72,6 +72,17 @@ export function validateChoice(options: any[]): Validator {
}
}
export function validateDateIso8601String(input: any): [any, any] {
const [value, error] = validateNonEmptyTrimmedString(input)
if (error !== null) {
return [value, error]
}
if (!iso8601DateRegExp.test(value)) {
return [value, "Invalid date"]
}
return [value, null]
}
export function validateEmpty(value: any): [any, any] {
return validateChain(validateEmptyToNull, validateMissing)(value)
}
......@@ -112,15 +123,38 @@ export function validateInteger(value: any): [any, any] {
return [value, null]
}
export function validateDateIso8601String(input: any): [any, any] {
const [value, error] = validateNonEmptyTrimmedString(input)
if (error !== null) {
return [value, error]
export function validateKeyValueDictionary(keyValidator: Validator, valueValidator:Validator): Validator {
return function(dict: any): [any, any] {
if (dict === null || dict === undefined) {
return [dict, "Missing value"]
}
if (!iso8601DateRegExp.test(value)) {
return [value, "Invalid date"]
if (typeof dict !== "object") {
return [dict, `Expected an object, got "${typeof dict}"`]
}
if (keyValidator === null || keyValidator === undefined) {
keyValidator = (key => [key, null])
}
if (valueValidator === null || valueValidator === undefined) {
valueValidator = (value => [value, null])
}
const errors: { [key: string]: any } = {}
const validatedDict: { [key: string]: any } = {}
for (const [key, value] of Object.entries(dict)) {
const [validatedKey, keyError] = keyValidator(value)
if (keyError !== null) {
errors[key] = `Key error: ${keyError}`
continue
}
const [validatedValue, valueError] = valueValidator(value)
validatedDict[validatedKey] = validatedValue
if (valueError !== null) {
errors[validatedKey] = valueError
}
}
return [validatedDict, Object.keys(errors).length === 0 ? null : errors]
}
return [value, null]
}
export function validateMaybeTrimmedString(value: any): [any, any] {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment