Coder's Cat

Form Validator In Svelte


I begin to write some tutorials on learning Svelte. Again, I’m also a new front-end developer, so I’m not sure if I’m doing is the best practice.

I will follow the project list of vanillawebprojects, try to re-implement the projects with Svelte.
I think this is a good way to practice front-end development skills.

Ok, let’s go to the Svelte Form Validator project.

It’s a simple form validator, which will be commonly used in registration UI.


Let’s create the project directory with the following command:

npx degit sveltejs/template form-validator
cd form-validator
npm install
npm run dev

Access http://localhost:5000 will show the demo HTML page.

The basic structure of a Svelte component is like this:

// Component logic goes here

<!-- HTML goes here -->

/* CSS goes here (scoped by default!) */

Here, let’s begin with some JavaScript variables, which will be used in validation.

let username = "";
let email = "";
let password = "";
let password2 = "";

Bind values

Then we will bind the variablesw in HTML elements with bind:value attribute, and hook the handleSubmit function to the on:click event.

<div class="form-control">
<label for="username">Username</label>
<input type="text" bind:value={username} id="username"
placeholder="Ente username" />

<div class="form-control">
<label for="email">Email</label>
<input type="text" bind:value={email} id="email"
placeholder="Enter email" />

<button on:click={handleSubmit} type="submit">Submit</button>


Compared with vanilla JavaScript, we don’t need to use getElementById to get the HTML elements. The code will be shorter as well. The core logic to do validation is like this:

// Event listeners	
function handleSubmit(e) {
if (!checkRequired([["username", username], ["email", email],
["password", password], ["password2", password2]])) {
checkLength("username", username, 3, 15);
checkLength("password", password, 6, 25);
checkPasswordsMatch(password, password2);

To make code shorter, we can use the required attribute to avoid manual checking:

<div class="form-control">
<label for="username">Username</label>
<input type="text" bind:value={username} id="username" placeholder="Enter username" required>


<button on:submit={handleSubmit} type="submit">Submit</button>

The refactor code commit is at this.

That’s all, the whole project is at : form-validator for your reference.

Join my Email List for more insights, It's Free!😋