Skip to content

Instantly share code, notes, and snippets.

@Joe-noh
Last active January 1, 2020 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Joe-noh/9e0446770849b8b2e211985d0ebd6676 to your computer and use it in GitHub Desktop.
Save Joe-noh/9e0446770849b8b2e211985d0ebd6676 to your computer and use it in GitHub Desktop.
Svelte validator prototype
<script>
import { createValidator } from '../stores/validator'
import TextInput from '../components/TextInput.svelte'
const [valueStore, errorStore, command] = createValidator({
type: 'string',
rules: [
{ required: true },
{ length: { min: 4, max: 10 } }
]
})
</script>
<TextInput on:blur="{command.activate}" bind:value="{$valueStore}" />
<span>Violated: {$errorStore}</span>
import { writable, derived } from 'svelte/store'
export function createValidator(opts) {
const { type, rules } = opts
const validator = createValidatorFun(rules)
const configStore = writable({ enabled: (opts.immediate === true) })
const valueStore = writable(initialValue(type))
const errorStore = derived([valueStore, configStore], ([value, config]) => {
return config.enabled ? validator(value) : []
})
const command = {
activate() {
configStore.update(config => ({ ...config, enabled: true }))
}
}
return [valueStore, errorStore, command]
}
function createValidatorFun(rules) {
return (value) => {
return rules.reduce((violated, rule) => {
const [[name, arg]] = Object.entries(rule)
if (name == 'required' && checkRequired(value, arg)) {
return [...violated, 'required']
} else if (name == 'length' && checkLength(value, arg)) {
return [...violated, 'length']
} else {
return violated
}
}, [])
}
}
function checkRequired(value, _) {
return !value
}
function checkLength(value, { min, max }) {
return (min !== undefined && value.length < min) || (max !== undefined && max < value.length)
}
function initialValue(type) {
if (type === 'string') {
return ''
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment