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:
|
Access http://localhost:5000 will show the demo HTML page.
The basic structure of a Svelte component is like this:
|
Here, let’s begin with some JavaScript variables, which will be used in validation.
|
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.
|
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:
|
To make code shorter, we can use the required
attribute to avoid manual checking:
|
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!😋