Skip to content

Instantly share code, notes, and snippets.

@helabenkhalfallah
Created April 10, 2024 20:02
Show Gist options
  • Save helabenkhalfallah/98462a44a8396170813efa74d0217c98 to your computer and use it in GitHub Desktop.
Save helabenkhalfallah/98462a44a8396170813efa74d0217c98 to your computer and use it in GitHub Desktop.
Svelte Form Example
<!-- Script Section -->
<script>
// Import the necessary functions from Svelte
import { createEventDispatcher } from 'svelte';
// Create a dispatcher for emitting custom events
const dispatch = createEventDispatcher();
// Define variables to store form data and validation errors
let username = '';
let email = '';
let password = '';
let confirmPassword = '';
let errors = {};
// Function to handle form submission
const handleSubmit = () => {
// Clear previous validation errors
errors = {};
// Perform validation checks
if (!username) {
errors.username = 'Username is required';
}
if (!email) {
errors.email = 'Email is required';
} else if (!isValidEmail(email)) {
errors.email = 'Invalid email format';
}
if (!password) {
errors.password = 'Password is required';
} else if (password.length < 6) {
errors.password = 'Password must be at least 6 characters long';
}
if (password !== confirmPassword) {
errors.confirmPassword = 'Passwords do not match';
}
// If there are no validation errors, dispatch form data
if (Object.keys(errors).length === 0) {
dispatch('submit', { username, email, password });
}
};
// Function to validate email format
const isValidEmail = (email) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
</script>
<!-- Form Markup -->
<form on:submit|preventDefault={handleSubmit}>
<label>
Username:
<input type="text" bind:value={username} />
<!-- Display username validation error if exists -->
{errors.username && <p class="error">{errors.username}</p>}
</label>
<label>
Email:
<input type="email" bind:value={email} />
<!-- Display email validation error if exists -->
{errors.email && <p class="error">{errors.email}</p>}
</label>
<label>
Password:
<input type="password" bind:value={password} />
<!-- Display password validation error if exists -->
{errors.password && <p class="error">{errors.password}</p>}
</label>
<label>
Confirm Password:
<input type="password" bind:value={confirmPassword} />
<!-- Display confirm password validation error if exists -->
{errors.confirmPassword && <p class="error">{errors.confirmPassword}</p>}
</label>
<!-- Button to submit the form -->
<button type="submit">Submit</button>
</form>
<!-- Style Section -->
<style>
.error {
color: red;
font-size: 0.8rem;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment