You will add custom validation to a form in Svelte using svelte-forms-lib, we will explore using the errors
store and the validate
option in order to validate a form before submission.
Instructor: [0:00] We have our form that is used in Svelte forms lib. Now, we want to create some validation to ensure that a user cannot submit an empty form. Let's add a property called validate to our createForm function config.
[0:12] This property is a function that passes the values of the field and return an error object. Create the variable called errors and assign an empty object to it. Then return the error variable. Now, let's check if our user name has any value by doing an if values.username= an empty string, then we add a new property to the errors object with a message that the field is required.
[0:36] If we hit Sign in, we will notice that no values are being logged out, so the onSubmit function is not being triggered because there is an error. Let's add errors to the destructured arguments that we get from the createForm function.
[0:49] Inside of our HTML, below our form input, let's display an error message if we have an empty username field. Here is some code I just pasted with what we want our validation message to look like. Let's wrap this validation message block of code with an if tag. Inside of our if tag, we will check if $errors.username is not empty.
[1:09] In between our small tag we will add our $errors.username to display the message. Let's hit the Sign in button again, and we should now see a message.
[1:19] Let's do the same for our password field. Inside of our validate function, we will add a check for our password along with its message and do the same in the HTML below our password input field. We will just copy and paste this and change username to password. Now, we can test again in the browser by clicking the Sign in button. We should now see an error.
[1:36] Let's enter some values, and we can now see our output in the console.