Skip to content

Instantly share code, notes, and snippets.

@farism
Last active February 28, 2020 16:34
Show Gist options
  • Save farism/467cb337222c573c15564e6c7e71d648 to your computer and use it in GitHub Desktop.
Save farism/467cb337222c573c15564e6c7e71d648 to your computer and use it in GitHub Desktop.
Form
<script>
import * as yup from 'yup'
let schema = yup.object({
isBig: yup.boolean(),
count: yup
.number()
.when('isBig', {
is: true,
then: yup.number().min(5),
otherwise: yup.number().min(0),
})
.required(),
count2: yup
.number()
.when('isBig', {
is: true,
then: yup.number().min(10),
otherwise: yup.number().min(0),
})
.when('count', (count, schema) => {
return count > 0 ? schema.min(count) : schema
})
.required(),
count3: yup
.number()
.when('isBig', {
is: true,
then: yup.number().min(15),
otherwise: yup.number().min(0),
})
.required(),
})
let form = {
isBig: false,
count: 0,
count2: 0,
count3: 0,
}
$: validForm = null
$: errors = []
$: {
schema
.validate(form, { abortEarly: false })
.then(value => {
errors = []
validForm = value
})
.catch(err => {
errors = err.inner || []
validForm = null
})
}
</script>
<label>
isBig: ({form.isBig})
<input type="checkbox" bind:checked="{form.isBig}" />
<input type="number" bind:value="{form.count}" />
<input type="number" bind:value="{form.count2}" />
<input type="number" bind:value="{form.count3}" />
errors: {#each errors as error}
<div>{error.path} - {error.message}</div>
{/each}
</label>
<button disabled="{!validForm}">submit</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment