Last active
January 1, 2020 18:49
-
-
Save Joe-noh/9e0446770849b8b2e211985d0ebd6676 to your computer and use it in GitHub Desktop.
Svelte validator prototype
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
<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> |
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
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