Form Validation with Svelte

Form Validation with Yup

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).

	// 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 };
		}, {});

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