Browsers have support for client side validation of form data built in. We can use this along with server side validation to give the user a nice experience and ensure security on the back end.
In the following form we use an email type and a required attribute. The browser will now block form submission until the field is filled in with a valid email address and password.
We can write this same form using Dioxus. Update
crates/ui-components/src/users.rs with a form to add users.
use crateLayout; use User; use *; // Take a Vec<User> and create an HTML table.
type are Rust keywords. We must prefix them with
r# so Rust knows that we want the raw string literal of "for" and "type".
Handling form submission
We need to install serde to transform the HTTP body into a Rust struct.
use crateCustomError; // 👇 update axum imports use ; // 👇 new import use Deserialize; use SocketAddr; async async // 👇 create new SignUp struct // 👇 handle form submission async
We are using
db::queries::users::create_user() in our
accept_form handler. We must also update
crates/db/queries/users.sql to include our actual SQL query
--: User() --! get_users : User SELECT id, email FROM users; -- 👇 add `create_user` query --! create_user INSERT INTO users (email, hashed_password) VALUES(:email, :hashed_password);
You should get results like the screenshot below.
If you add an email to the form and press submit, the server should handle that request and update the users table.
Server Side Validation
Our web form validates that the user input is an email. We should also check that the user input is an email on the server. We can use Validator which will allow us to add validation to the
use crateCustomError; // 👇 update axum imports use ; use Deserialize; use SocketAddr; // 👇 new import use Validate; async async async
And we can test that our validation works by sending a request directly to the server (bypassing the browser form):