Svelte is an open-source JavaScript framework to build efficient and high-performance web applications. It provides a simple and efficient way to create forms. Forms play a crucial role in user engagement by enabling them to register on a site or provide feedback. A basic form can be created in Svelte by defining the HTML structure and binding the form elements to variables.
Form validation is a crucial component of developing websites. It ensures that users enter accurate data in the provided format/fields. It is mandatory to maintain the integrity and functionality of user input-dependent systems. Svelte provides an easy way to use conditional logic and feedback messages to implement form validation.
We can view the result below and better understand how the form will look before developing a validation form in Svelte.
We must define the following to create a validation form in Svelte:
JavaScript logic for the form component.
The HTML structure of the form component.
Component style using CSS.
The primary logic of our validation form resides in this component. It is the key component for developing interactive web apps in Svelte. In the code snippet below, variables for storing user input for name, email, phone number, gender, and date of birth are declared. Error variables are also created for each input field to save validation error messages.
<script>let name = "";let email = "";let number = "";let dob = "";let gender = "Male";let nameError = "";let emailError = "";let numberError = "";let dobError = "";const validateForm = () => {nameError = validateName(name);emailError = !isValidEmail(email) ? "Invalid email address" : "";numberError = !isValidNumber(number) ? "Invalid number" : "";dobError = !isValidDOB(dob) ? "Invalid date of birth" : "";if (!nameError && !emailError && !numberError && !dobError) {if (compareDates(dob)) {alert("Form submitted successfully!");} else {dobError = "Date of birth cannot be greater than the current date";}}};const validateName = (name) => {if (name.trim() === "") {return "Name is required";} else if (/[^a-zA-Z\s]/.test(name)) {return "Name should only contain letters and spaces";}return "";};const isValidEmail = (email) => {const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;return email.match(emailRegex);};const isValidNumber = (number) => {const numberRegex = /^\d{7,12}$/;return number.match(numberRegex);};const isValidDOB = (dob) => {const dobRegex = /^\d{4}-\d{2}-\d{2}$/;return dob.match(dobRegex);};const compareDates = (dob) => {const currentDate = new Date();const inputDate = new Date(dob);return inputDate <= currentDate;};</script>
This section explains the component’s HTML structure, which includes the button, validation form, and other relevant element:
<main><h2>Form Validation in Svelte</h2><form><label for="name">Name:</label><input type="text" id="name" bind:value={name} on:input={() => nameError = ""} placeholder="John" /><p class="error">{nameError}</p><label for="email">Email:</label><input type="email" id="email" bind:value={email} on:input={() => emailError = ""} placeholder="john@gmail.com"/><p class="error">{emailError}</p><label for="number">Number:</label><input type="text" id="number" bind:value={number} on:input={() => numberError = ""} placeholder="0000000" /><p class="error">{numberError}</p><label for="dob">Date of Birth:</label><input type="text" id="dob" bind:value={dob} on:input={() => dobError = ""} placeholder="2010-10-10"/><p class="error">{dobError}</p><label for="gender">Gender:</label><select id="gender" bind:value={gender}><option value="Male">Male</option><option value="Female">Female</option><option value="Other">Other</option></select><button type="button" on:click={validateForm}>Submit</button></form></main>
Creating a visually beautiful and user-friendly validation form greatly depends on style. The code snippet below gives our validation form application some style:
<style>main {max-width: 300px;margin: 0 auto;text-align: center;}label {display: block;margin-top: 10px;}input {width: 100%;padding: 5px;margin-top: 5px;}button {width: 100%;margin-top: 10px;background-color: #007bff;color: white;border: none;padding: 10px 15px;cursor: pointer;}.error {color: red;margin-top: 10px;}</style>
The complete code of form validation in Svelte is given in the src/App.svelte
file:
<script> let name = ""; let email = ""; let number = ""; let dob = ""; let gender = "Male"; let nameError = ""; let emailError = ""; let numberError = ""; let dobError = ""; const validateForm = () => { nameError = validateName(name); emailError = !isValidEmail(email) ? "Invalid email address" : ""; numberError = !isValidNumber(number) ? "Invalid number" : ""; dobError = !isValidDOB(dob) ? "Invalid date of birth" : ""; if (!nameError && !emailError && !numberError && !dobError) { if (compareDates(dob)) { alert("Form submitted successfully!"); } else { dobError = "Date of birth cannot be greater than the current date"; } } }; const validateName = (name) => { if (name.trim() === "") { return "Name is required"; } else if (/[^a-zA-Z\s]/.test(name)) { return "Name should only contain letters and spaces"; } return ""; }; const isValidEmail = (email) => { const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; return email.match(emailRegex); }; const isValidNumber = (number) => { const numberRegex = /^\d{7,12}$/; return number.match(numberRegex); }; const isValidDOB = (dob) => { const dobRegex = /^\d{4}-\d{2}-\d{2}$/; return dob.match(dobRegex); }; const compareDates = (dob) => { const currentDate = new Date(); const inputDate = new Date(dob); return inputDate <= currentDate; }; </script> <main> <h2>Form Validation in Svelte</h2> <form> <label for="name">Name:</label> <input type="text" id="name" bind:value={name} on:input={() => nameError = ""} placeholder="John" /> <p class="error">{nameError}</p> <label for="email">Email:</label> <input type="email" id="email" bind:value={email} on:input={() => emailError = ""} placeholder="john@gmail.com"/> <p class="error">{emailError}</p> <label for="number">Number:</label> <input type="text" id="number" bind:value={number} on:input={() => numberError = ""} placeholder="0000000" /> <p class="error">{numberError}</p> <label for="dob">Date of Birth:</label> <input type="text" id="dob" bind:value={dob} on:input={() => dobError = ""} placeholder="2010-10-10"/> <p class="error">{dobError}</p> <label for="gender">Gender:</label> <select id="gender" bind:value={gender}> <option value="Male">Male</option> <option value="Female">Female</option> <option value="Other">Other</option> </select> <button type="button" on:click={validateForm}>Submit</button> </form> </main> <style> main { max-width: 300px; margin: 0 auto; text-align: center; } label { display: block; margin-top: 10px; } input { width: 100%; padding: 5px; margin-top: 5px; } button { width: 100%; margin-top: 10px; background-color: #007bff; color: white; border: none; padding: 10px 15px; cursor: pointer; } .error { color: red; margin-top: 10px; } </style>
Lines 1–56: This section contains the JavaScript code for validating the form.
Lines 2–10: We define and initialize variables.
Lines 12–25: We define the validateForm
function that will be responsible for validating different fields of the form.
Lines 27–34: This is the validateName
function for name validation, which allows characters and spaces only; the name field cannot be empty.
Lines 36–39: This is the isValidEmail
function for email validation, which must contain @
and .
symbols in it.
Lines 41–44: This is the isValidNumber
function for number validation.
Lines 46–55: These are isValidDOB
and comparesDates
functions that are used for date of birth validation.
Lines 57–85: This part contains the HTML structure or main content of web page.
Lines 87–119: This section contains the styling of form elements.
In this Answer, we went through the form validation in Svelte, which makes sure that the data entered by the user meets certain patterns or requirements. Svelte provides an efficient and convenient way to implement form validation.