feat: add form validation

This commit is contained in:
Divlo
2022-08-25 23:24:40 +02:00
parent c9bb631073
commit 17656c149a
13 changed files with 333 additions and 31 deletions

24
src/utils/ajv.ts Normal file
View File

@ -0,0 +1,24 @@
import addFormats from 'ajv-formats'
import Ajv from 'ajv'
export const ajv = addFormats(
new Ajv({
allErrors: true
}),
[
'date-time',
'time',
'date',
'email',
'hostname',
'ipv4',
'ipv6',
'uri',
'uri-reference',
'uuid',
'uri-template',
'json-pointer',
'relative-json-pointer',
'regex'
]
)

View File

@ -0,0 +1,25 @@
import type { TObject } from '@sinclair/typebox'
import type { ObjectAny } from './types'
export const handleCheckboxBoolean = (
object: ObjectAny,
validateSchemaObject: TObject<ObjectAny>
): ObjectAny => {
const booleanProperties: string[] = []
for (const property in validateSchemaObject.properties) {
const rule = validateSchemaObject.properties[property]
if (rule.type === 'boolean') {
booleanProperties.push(property)
}
}
for (const booleanProperty of booleanProperties) {
if (object[booleanProperty] == null) {
object[booleanProperty] =
validateSchemaObject.properties[booleanProperty].default
} else {
object[booleanProperty] = object[booleanProperty] === 'on'
}
}
return object
}

View File

@ -0,0 +1,17 @@
export const handleOptionalEmptyStringToNull = <K>(
object: K,
required: string[] = []
): K => {
return Object.fromEntries(
Object.entries(object).map(([key, value]) => {
if (
typeof value === 'string' &&
value.length === 0 &&
!required.includes(key)
) {
return [key, null]
}
return [key, value]
})
) as K
}

3
src/utils/types.ts Normal file
View File

@ -0,0 +1,3 @@
export interface ObjectAny {
[key: string]: any
}