Coder's Cat

Form Validator In Svelte

2021-11-30

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:

<script>
// Component logic goes here
</script>

<!-- HTML goes here -->

<style>
/* CSS goes here (scoped by default!) */
</style>

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

<script>
let username = "";
let email = "";
let password = "";
let password2 = "";
...
</script>

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" />
<small></small>
</div>

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

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

Validation

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) {
e.preventDefault();
if (!checkRequired([["username", username], ["email", email],
["password", password], ["password2", password2]])) {
checkLength("username", username, 3, 15);
checkLength("password", password, 6, 25);
checkEmail(email);
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>
<small></small>
</div>

...

<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!😋