Bird
Raised Fist0
Svelteframework~20 mins

Form validation in Svelte - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Form Validation Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when submitting a form with empty required fields?

Consider this Svelte form with two required inputs. What happens when the user submits the form without filling any fields?

Svelte
<script>
  let name = '';
  let email = '';
  let error = '';
  function handleSubmit() {
    if (!name || !email) {
      error = 'Please fill all required fields.';
    } else {
      error = '';
    }
  }
</script>
<form on:submit|preventDefault={handleSubmit} aria-label="User form">
  <label for="name">Name:</label>
  <input id="name" type="text" bind:value={name} aria-required="true" />
  <label for="email">Email:</label>
  <input id="email" type="email" bind:value={email} aria-required="true" />
  <button type="submit">Submit</button>
  {#if error}
    <p role="alert" style="color: red;">{error}</p>
  {/if}
</form>
AThe form shows the error message 'Please fill all required fields.' below the button.
BThe browser shows a native tooltip error for the first empty required input.
CThe form submits successfully and clears the inputs.
DNothing happens; the form silently fails without feedback.
Attempts:
2 left
💡 Hint

Look at the handleSubmit function and the error variable usage.

📝 Syntax
intermediate
2:00remaining
Which option correctly validates an email input in Svelte?

Which code snippet correctly updates an emailError message when the email input is invalid?

Svelte
<script>
  let email = '';
  let emailError = '';
  function validateEmail() {
    // validation logic here
  }
</script>
<input type="email" bind:value={email} on:input={validateEmail} aria-describedby="email-error" />
<p id="email-error" role="alert" style="color: red;">{emailError}</p>
A
function validateEmail() {
  emailError = email.match(/^[^@]+@[^@]+\.[^@]+$/) ? '' : 'Invalid email address';
}
B
function validateEmail() {
  emailError = email.includes('@') ? '' : 'Invalid email address';
}
C
function validateEmail() {
  if (!email.includes('@')) {
    emailError = 'Invalid email address';
  } else {
    emailError = '';
  }
}
D
function validateEmail() {
  emailError = email.length &gt; 5 ? '' : 'Invalid email address';
}
Attempts:
2 left
💡 Hint

Check which option uses a proper email pattern to validate.

❓ state_output
advanced
2:00remaining
What is the value of formValid after input changes?

Given this Svelte code, what is the value of formValid after the user types 'user@example.com' in the email input and 'John' in the name input?

Svelte
<script>
  import { derived, writable } from 'svelte/store';
  const name = writable('');
  const email = writable('');
  const formValid = derived(
    [name, email],
    ([$name, $email]) => $name.trim().length > 0 && /^[^@]+@[^@]+\.[^@]+$/.test($email)
  );
</script>
<input type="text" bind:value={$name} aria-label="Name input" />
<input type="email" bind:value={$email} aria-label="Email input" />
Afalse
Bundefined
Cnull
Dtrue
Attempts:
2 left
💡 Hint

Check the derived store logic and the input values.

🔧 Debug
advanced
2:00remaining
Why does this Svelte form not show validation errors on submit?

Review this Svelte form code. The form submits even when inputs are empty, and no error message appears. What is the cause?

Svelte
<script>
  let username = '';
  let error = '';
  function submitForm(event) {
    event.preventDefault();
    if (!username) {
      error = 'Username required';
    }
  }
</script>
<form on:submit={submitForm} aria-label="Username form">
  <input type="text" bind:value={username} aria-required="true" />
  <button type="submit">Submit</button>
  {#if error}
    <p role="alert" style="color: red;">{error}</p>
  {/if}
</form>
AThe error variable is not reactive, so it never updates.
BThe form submits because the submit event is not prevented, so the page reloads before error shows.
CThe input is missing a name attribute, so validation fails silently.
DThe error message is outside the form, so it is not displayed.
Attempts:
2 left
💡 Hint

Check the form submission event handling.

🧠 Conceptual
expert
3:00remaining
Which approach best ensures accessible form validation feedback in Svelte?

Choose the best practice for showing validation errors that screen readers announce immediately after user input changes.

AUse <code>aria-hidden="true"</code> on error messages to avoid distraction.
BUse <code>role="alert"</code> on the error message and update it only on form submit.
CUse <code>aria-live="assertive"</code> on the error message container and update error text reactively.
DShow errors only as placeholder text in inputs without ARIA roles.
Attempts:
2 left
💡 Hint

Think about how screen readers detect live changes.

Practice

(1/5)
1. What is the main purpose of form validation in a Svelte application?
easy
A. To check user input before sending data
B. To style the form elements
C. To load data from the server
D. To create new components

Solution

  1. Step 1: Understand form validation role

    Form validation ensures user input is correct before submission.
  2. Step 2: Identify the correct purpose

    Checking input prevents errors and improves user experience.
  3. Final Answer:

    To check user input before sending data -> Option A
  4. Quick Check:

    Form validation = check input [OK]
Hint: Validation means checking input before sending [OK]
Common Mistakes:
  • Confusing validation with styling
  • Thinking validation loads data
  • Mixing validation with component creation
2. Which Svelte syntax correctly binds an input's value for validation?
easy
A.
B.
C.
D.

Solution

  1. Step 1: Recall Svelte binding syntax

    Svelte uses bind:value={variable} to bind input values.
  2. Step 2: Identify correct syntax

    <input bind:value={name} /> uses correct curly braces and binding keyword.
  3. Final Answer:

    <input bind:value={name} /> -> Option B
  4. Quick Check:

    bind:value with braces = correct [OK]
Hint: Use bind:value with curly braces for binding [OK]
Common Mistakes:
  • Omitting curly braces
  • Using colon instead of equals
  • Using value= instead of bind:value=
3. What will be the output when submitting this Svelte form if the input is empty?
<script>
  let email = '';
  let error = '';
  function validate() {
    if (!email) {
      error = 'Email is required';
    } else {
      error = '';
    }
  }
</script>

<form on:submit|preventDefault={validate}>
  <input bind:value={email} type="email" />
  <button type="submit">Submit</button>
  <p>{error}</p>
</form>
medium
A. Error message 'Email is required' is shown
B. Form submits with no error message
C. Syntax error prevents form rendering
D. Form reloads the page

Solution

  1. Step 1: Analyze validation function

    If email is empty, error is set to 'Email is required'.
  2. Step 2: Check form submission behavior

    Submit event is prevented from default, so page does not reload, and error message shows.
  3. Final Answer:

    Error message 'Email is required' is shown -> Option A
  4. Quick Check:

    Empty input triggers error message [OK]
Hint: Empty input triggers error message display [OK]
Common Mistakes:
  • Ignoring preventDefault causing page reload
  • Expecting form to submit without error
  • Confusing syntax error with logic error
4. Identify the error in this Svelte form validation code:
<script>
  let password = '';
  let error = '';
  function check() {
    if(password.length < 6) {
      error = 'Password too short';
    }
  }
</script>

<form on:submit={check}>
  <input bind:value={password} type="password" />
  <button type="submit">Login</button>
  <p>{error}</p>
</form>
medium
A. Incorrect binding syntax for password
B. Error message variable not declared
C. Missing preventDefault on submit event
D. Password length check uses wrong operator

Solution

  1. Step 1: Review submit event handling

    The form's submit event calls check but does not prevent default, so page reloads.
  2. Step 2: Identify missing preventDefault

    Without preventDefault, error message disappears on reload, breaking validation UX.
  3. Final Answer:

    Missing preventDefault on submit event -> Option C
  4. Quick Check:

    Submit needs preventDefault to stop reload [OK]
Hint: Always use preventDefault on form submit to keep validation visible [OK]
Common Mistakes:
  • Forgetting preventDefault causes page reload
  • Thinking binding syntax is wrong when it is correct
  • Assuming error variable is missing
5. How can you improve accessibility when showing validation errors in a Svelte form?
hard
A. Remove labels to reduce clutter
B. Use only color changes to show errors
C. Hide error messages visually but keep them in the DOM
D. Add aria-live="polite" to error message container

Solution

  1. Step 1: Understand accessibility for errors

    Screen readers need to be notified of error changes dynamically.
  2. Step 2: Use aria-live attribute

    Adding aria-live="polite" tells assistive tech to announce updates politely.
  3. Final Answer:

    Add aria-live="polite" to error message container -> Option D
  4. Quick Check:

    aria-live improves screen reader announcements [OK]
Hint: Use aria-live for dynamic error announcements [OK]
Common Mistakes:
  • Relying only on color changes (not accessible)
  • Hiding errors visually removes info from users
  • Removing labels harms form clarity
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard