Skip to content
This repository has been archived by the owner on Aug 28, 2020. It is now read-only.

form validation with yup #47

Merged
merged 1 commit into from
Jun 21, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 64 additions & 1 deletion components.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->

**Table of Contents**

- [Using Fetch to Consume APIs with Svelte](#using-fetch-to-consume-apis-with-svelte)
Expand Down Expand Up @@ -298,6 +299,7 @@ When you want to "forward" any attributes like `class` or `style` to your compon
<!-- App.svelte -->
<Component class="li-item-class">{name}</Component>
```

[Svelte Playground here](https://svelte.dev/repl/24139d8599d348b9bcad5c0a1f471230?version=3.23.0). See [relevant part of docs](https://svelte.dev/docs#Attributes_and_props) for more.

This is helpful where, for example, [using MDSveX](https://github.com/pngwn/MDsveX/), you want to create a bunch of Svelte wrappers to DOM elements like `H1`, `P`, and `A` instead of the normal `h1`, `p`, and `a`.
Expand All @@ -306,7 +308,68 @@ Note that when passing a class to component, you may need to set it to global `:

## Form Validation with Svelte

_to be written_
### Form Validation with Yup

[Yup](https://github.com/jquense/yup) is a JavaScript schema builder for value passing and validation. We can use Yup to help us validate forms in Svelte.

We can use `bind:value` to bind input value, and validate the form using `schema.validate(values)`.

```svelte
<script>
// Define schema with Yup
import * as yup from 'yup';
const schema = yup.object().shape({
email: yup
.string()
.required('Please provide your email')
.email("Email doesn't look right"),
password: yup.string().required('Password is required'),
});

let values = {};
let errors = {};

async function submitHandler() {
try {
// `abortEarly: false` to get all the errors
await schema.validate(values, { abortEarly: false });
alert(JSON.stringify(values, null, 2));
errors = {};
} catch (err) {
errors = extractErrors(err);
}
}
function extractErrors(err) {
return err.inner.reduce((acc, err) => {
return { ...acc, [err.path]: err.message };
}, {});
}
</script>

<form on:submit|preventDefault={submitHandler}>
<div>
<input
type="text"
name="email"
bind:value={values.email}
placeholder="Your email"
/>
{#if errors.email}{errors.email}{/if}
</div>
<div>
<input
type="password"
name="password"
bind:value={values.password}
placeholder="Password"
/>
{#if errors.password}{errors.password}{/if}
</div>
<div>
<button type="submit">Register</button>
</div>
</form>
```

## Client-Side Storage with Svelte

Expand Down