1
0
Fork 0
mirror of synced 2024-07-08 15:56:23 +12:00

Validation observe

This commit is contained in:
Adria Navarro 2023-06-13 12:42:30 +01:00
parent 32dde23728
commit 7cfb47c287
2 changed files with 60 additions and 11 deletions

View file

@ -13,18 +13,10 @@
let includeInternalTablesRows = true
let encypt = true
let password
let password = null
const validation = createValidationStore()
validation.addValidatorType("password", "password", "true")
function validate() {
return validation.check({ password })
}
$: {
if ($validation.errors.length) {
validate()
}
}
$: validation.observe("password", password)
const Step = { CONFIG: "config", SET_PASSWORD: "set_password" }
let currentStep = Step.SET_PASSWORD
@ -42,17 +34,19 @@
return false
}
},
isValid: true,
},
[Step.SET_PASSWORD]: {
title: "Add password to encrypt your export",
confirmText: exportButtonText,
onConfirm: async () => {
await validate()
await validation.check({ password })
if (!$validation.valid) {
return false
}
exportApp()
},
isValid: $validation.valid,
},
}
@ -67,6 +61,7 @@
title={stepConfig[currentStep].title}
confirmText={stepConfig[currentStep].confirmText}
onConfirm={stepConfig[currentStep].onConfirm}
disabled={!stepConfig[currentStep].isValid}
>
{#if currentStep === Step.CONFIG}
<Body>

View file

@ -5,6 +5,7 @@ import { notifications } from "@budibase/bbui"
export const createValidationStore = () => {
const DEFAULT = {
values: {},
errors: {},
touched: {},
valid: false,
@ -44,6 +45,58 @@ export const createValidationStore = () => {
validator[propertyName] = propertyValidator
}
const observe = async (propertyName, value) => {
const values = get(validation).values
let fieldIsValid
if (!values.hasOwnProperty(propertyName)) {
// Initial setup
values[propertyName] = value
return
}
if (value === values[propertyName]) {
return
}
const obj = object().shape(validator)
try {
validation.update(store => {
store.errors[propertyName] = null
return store
})
await obj.validateAt(propertyName, { [propertyName]: value })
fieldIsValid = true
} catch (error) {
const [fieldError] = error.errors
if (fieldError) {
validation.update(store => {
store.errors[propertyName] = capitalise(fieldError)
store.valid = false
return store
})
}
}
if (fieldIsValid) {
// Validate the rest of the fields
try {
await obj.validate(
{ ...values, [propertyName]: value },
{ abortEarly: false }
)
validation.update(store => {
store.valid = true
return store
})
} catch {
validation.update(store => {
store.valid = false
return store
})
}
}
}
const check = async values => {
const obj = object().shape(validator)
// clear the previous errors
@ -87,5 +140,6 @@ export const createValidationStore = () => {
check,
addValidator,
addValidatorType,
observe,
}
}